从对象数组递归创建JSON树结构 [英] Recursively creating a JSON tree structure from arrays of objects
问题描述
以下是我的数据结构:
{ projects: [
{ revisions: [
{ files: [] },
],
}
],
user: {}
}
在这里转到jsFiddle: http:// jsfiddle .net / winduptoy / EXdDy /
Go to the jsFiddle here: http://jsfiddle.net/winduptoy/EXdDy/
我正在以递归方式创建对象父母的JSON层次结构及其 ID
秒。检查你的控制台。查看 projects [0] .revisions [0] ._ idTree
,其中包含 projects._id
和修订
作为 子 的项目
,正如预期的那样。现在看看 projects [0] .revisions [0] .files [0] ._ idTree
,其中包含 projects.files
作为 兄弟 的 projects.revisions
,当 files
应该是 projects.revisions
的 孩子 。我该如何解决这个问题?
I'm tyring to recursively create a JSON hierarchy structure of an object's parents and their id
s. Check your console. Look at projects[0].revisions[0]._idTree
, which contains the projects._id
and revisions
as a child of projects
, just as expected. Now look at projects[0].revisions[0].files[0]._idTree
, which contains projects.files
as a sibling of projects.revisions
, when files
should be a child of projects.revisions
. How do I fix this?
推荐答案
请像这样重写 recurseTree
:
function recurseTree(tree, newKey, newId) {
if(angular.element.isEmptyObject(tree)) {
tree[newKey] = {_id: newId};
return;
}
var child = null; // find current tree's child
for(var key in tree) {
if (key != '_id') {
child = tree[key]; // found a child
break;
}
}
if (child) { // recursively process on child
recurseTree(child, newKey, newId);
} else { // no child, so just fill the tree
tree[newKey] = {_id: newId};
}
}
这篇关于从对象数组递归创建JSON树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!