gpt4 book ai didi

javascript - 从对象数组递归创建 JSON 树结构

转载 作者:行者123 更新时间:2023-11-30 18:13:08 26 4
gpt4 key购买 nike

这是我的数据结构:

{ projects: [
{ revisions: [
{ files: [] },
],
}
],
user: {}
}

转到此处的 jsFiddle:http://jsfiddle.net/winduptoy/EXdDy/

我很想递归地创建一个对象的父对象及其 id 的 JSON 层次结构秒。检查你的控制台。看projects[0].revisions[0]._idTree ,其中包含 projects._idrevisions作为 projects child ,正如预期的那样。现在看projects[0].revisions[0].files[0]._idTree ,其中包含 projects.files作为 projects.revisions sibling , 当 files应该是 projects.revisions child .我该如何解决这个问题?

最佳答案

请像这样重写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};
}
}

关于javascript - 从对象数组递归创建 JSON 树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com