2014-02-21 24 views
2

我正在尝试不同的方法到my previous question。基本上,我有一个JSON对象,看起来像这样:重新格式化节点中的JSON树

var data = { 
    "tree": { 
     "id": "99842", 
     "label": "Bill", 
     "children": [ 
      { 
       "id": "27878", 
       "label": "Tom", 
       "children": [] 
      } 
     ] 
    }, 
    "index": { 
     "27878": { 
      "birthdate": "1/21/1988", 
      "spouse": "June", 
      "hometown": "Tulsa, OK" 
     }, 
     "99842": { 
      "birthdate": "4/15/1969", 
      "spouse": "Mary", 
      "hometown": "Dallas, TX" 
     } 
    } 
}; 

正如你可以看到,有两个“顶级”项目:“树”对象和“索引”的对象。我想分析他们共同获得此:

{ 
    "rows": [ 
     { 
      "id": "99842", 
      "data": [ 
       { 
        "birthdate": "4/15/1969", 
        "spouse": "Mary", 
        "hometown": "Dallas, TX" 
       } 
      ], 
      "rows": [ 
       { 
        "id": "27878", 
        "data": [ 
         { 
          "birthdate": "1/21/1988", 
          "spouse": "June", 
          "hometown": "Tulsa, OK" 
         } 
        ], 
        "rows": [] 
       } 
      ] 
     } 
    ] 
} 

好像我可以做递归与Q,但它似乎像矫枉过正,我有一个很难让我的头缠着。我想通过回调的解决方案,但还没有完成。我会很感激任何帮助。

+1

那里没有什么看起来异步。你为什么想着'Q'或回调?你不能做简单的同步递归吗? –

+0

@AaronDufour - 我想我很难让我的头在节点递归。但是,也许我让它比实际上更难。 –

回答

3

递归似乎完全合理。这里有一个可能的解决方案:

function nestObjects(tree, index) { 

    var output; 

    if (tree && index) { 

     output = { 
      id: tree.id, 
      data: index[tree.id], 
      rows: [] 
     }; 

     if (Array.isArray(tree.children) && tree.children.length) { 

      for (var i = 0, len = tree.children.length; i < len; i++) { 

       output.rows.push(nestObjects(tree.children[i], index)); 
      } 
     } 
    } 

    return output; 
} 

var result = { 
    rows: [nestObjects(data.tree, data.index)] 
}; 

console.log(result); 
+0

我有点尴尬,这很容易。我不知道为什么我认为它会要求回调或者Node-ish。谢谢。 –

+0

没有汗!我花了一段时间才把自己的头脑包装在异步风格的编程和回调(并知道何时不需要)。干杯。 :) – prattsj