Skip to content Skip to sidebar Skip to footer

Javascript Nested Object To Multidimensional Array Recursive Function

Ok here's one at which I've been scratching my head at without great success so far; Sorry in advance for the very long question... I am using this Lucene Query Parser to parse a s

Solution 1:

I think this ought to do it:

createGroups = (item, previousGroup) ->
  subroutine = (item, previousGroup) ->
    if typeof item is "object"
      unless item.operator
        if !item.left
          previousGroup.push item  
        else
          previousGroup.push item.left
        previousGroup
      if item.operator is "AND"
        currentGroup = subroutine(item.left, previousGroup)
        currentGroup = subroutine(item.right, currentGroup)
        currentGroup and groups.push(currentGroup)
      if item.operator is "OR"
        currentGroup = subroutine(item.left, previousGroup)
        groups.push currentGroup
        currentGroup and subroutine(item.right, [])
    return

  previousGroup = previousGroup or []
  subroutine item, previousGroup
  groups

createGroups o

Post a Comment for "Javascript Nested Object To Multidimensional Array Recursive Function"