重新格式化节点中的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" } } }; 

正如你所看到的,有两个“顶级”项目:一个“树”对象和一个“索引”对象。 我想一起parsing它们来得到这个:

 { "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做recursion,但是看起来好像过火了,而且我很难把它缠绕在头上。 我想通过callback的解决scheme,但还没有完成。 我会很感激任何帮助。

recursion似乎是完全合理的。 这是一个可能的解决scheme:

 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);