gpt4 book ai didi

javascript - 如何在从根遍历到json树的目标 Node 时插入键?

转载 作者:行者123 更新时间:2023-11-30 13:46:51 25 4
gpt4 key购买 nike

假设我的 JSON 树将具有如下结构

 var tree = [{
iriID: "/api/catalogs/7",
id: 7,
name: "drywall",

children: [{
iriID: "/api/catalogs/11",
id: 11,
name: "Vipuls catalog",

children: [{
iriID: "/api/catalogs/10",
id: 10,
name: "test catalog 3",

children: []
},
{
iriID: "/api/catalogs/9",
id: 9,
name: "test catalog",

children: []
}
]
},

]
},


];

我想在从第一个 Node 遍历到 id=9 的 Node 时插入一个键 travelled=true 。最终输出应如下所示。

      var tree = [{
iriID: "/api/catalogs/7",
id: 7,
name: "drywall",
traversed: true,
children: [{
iriID: "/api/catalogs/11",
id: 11,
name: "Vipuls catalog",
traversed: true,
children: [{
iriID: "/api/catalogs/10",
id: 10,
name: "test catalog 3",

children: []
},
{
iriID: "/api/catalogs/9",
id: 9,
name: "test catalog",
traversed: true,
children: []
}
]
},

]
},


];

希望您理解我的要求。请确保用于查找最短路径的代码经过优化并且功能良好。

最佳答案

我会使用递归函数来收集目标 Node 路径上的 Node 。然后你可以决定对该路径上的 Node 做你想做的事,例如给他们额外的属性(property):

function getPathTo(nodes, id) {
for (let node of nodes) {
if (node.id === id) return [node];
let path = getPathTo(node.children || [], id);
if (path) return [node, ...path];
}
}

// Demo
var tree = [{iriID: "/api/catalogs/7",id: 7,name: "drywall",children: [{iriID: "/api/catalogs/11",id: 11,name: "Vipuls catalog",children: [{iriID: "/api/catalogs/10",id: 10,name: "test catalog 3",children: []}, {iriID: "/api/catalogs/9",id: 9,name: "test catalog",children: []}]}]}];
let path = getPathTo(tree, 9) || [];
console.log(path.map(node => node.id));
path.forEach(node => node.traversed = true);
console.log(tree);

关于javascript - 如何在从根遍历到json树的目标 Node 时插入键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138446/

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