2014-04-12 3 views
0

여기까지 큰 성공없이 내 머리를 긁적 거렸다. ... 아주 긴 질문에 미리 죄송합니다Javascript 다차원 배열의 재귀 함수에 중첩 된 객체

내가 데이터 구조의 이러한 종류의 생산 문자열/쿼리 구문 분석이 Lucene Query Parser을 사용하고 있습니다 :

// Notice that the repetition of 'field3' is on purpose 
Sample String: field1:val1 AND field2:val2 OR field3:val3 AND field3:val4 
Result: 
    { left: { field: "field1", term: "val1" }, 
     operator: "AND" 
     right: { 
      left: { field: "field2", term: "val2" }, 
      operator: "OR" 
      right: { 
       left: {field: "field3", term: "val3" }, 
       operator: "AND", 
       right: { 
        field: "field3", 
        term: "val4" 
       } 
      } 
     } 

내가 그것에 반복 할 필요를 객체가 다음 얻기 위해 각 개체 INSI 동안 나는 이것을 설명하려고하면

[ [{ field: "field1", term: "val1"}, 
    { field: "field2", term: "val2"} 
    ], 
    [{ field: "field3", term: "val3"}, 
    { field: "field3", term: "val4"} 
    ] 
] 

을, 아이디어는, 각각의 아이 배열은 "OR"로 구분되는 배열의 배열을 만드는 것입니다 de 자식 배열은 "AND"로 구분 된 필드를 나타냅니다. 나는 위의 코드보다 더 나은 설명 생각하지만 나

업데이트 코드 (죄송 coffeescriptlo-dash) :

groups = []  
createGroups = (item, previousGroup, previousOperator) -> 
    currentGroup = if _.isArray previousGroup then previousGroup else [] 

    # keyVal = {} 
    # keyVal[item.left?.field or item.field] = item.left?.term or item.term 
    obj = fieldName: item.left?.field or item.field, val: item.left?.term or item.term 

    if previousOperator?.toUpperCase() is 'AND' 
     currentGroup.push obj 
    else 
     currentGroup = [obj] 

    if _.isObject item.right 
     createGroups(item.right, currentGroup, item.operator) 

    groups.push currentGroup 

이 코드는 작동하고, 거의 내가하고 싶은 일을하지만 의지 groups 배열은 함수 밖에서 선언되어야하지만, 함수 내에서 직접적으로 사용되는 것은 이상적이지는 않지만 필자와 함께 살 수 있습니다.

그러나, 그것은과 같이 모든 그룹을 복제합니다

[ [ {field: "field1", val:val1}, {field: "field2" val:val2} ], [ {field: "field1":val1}, {field: "field2", val:val2} ], ...] 

을 지금 나는 위의 함수는 올바른 결과를 반환하는 경우 내가해야 할 야해 작업 인 _.uniq(groups)를 사용할 필요가

당신의 도움에 대한

덕분에

답변

1

은 내가 그것을 할한다고 생각한다

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 
+0

매력처럼 작동하는 것 같습니다 –

+0

사실 저는이 코드가 하나의 "왼쪽"속성이있는 이벤트를 고려하지 않을 것임을 실제로 깨달았습니다 : '{왼쪽 : [Object object]} ' 기회가있을 때마다 빠른 수정을위한 아이디어가 있습니까? –

+0

수정되었지만 테스트하지 않았습니다 ... – adrichman

관련 문제