gpt4 book ai didi

javascript - 递归循环对象树

转载 作者:行者123 更新时间:2023-11-29 10:59:03 25 4
gpt4 key购买 nike

我有树对象:

const tree = [
{
key: "parent1",
id: "001",
children:[{ key: "B", id: "002", children: [{key: "C", id: "003", children: [{key: "D", id: "004", children: [] }]}], }]
},
{
key: "parent2",
id: "002",
children:[{ key: "B", id: "002", children: [{key: "C", id: "003", children: [{key: "D", id: "004", children: [] }]}], }]
},
]

我想循环遍历树,但我只得到 2 层:

tree.map((parentNode) => {
console.log(`parentNode: ${parentNode.key}`);
const childrenNode = parentNode.children;
childrenNode.map((childNode) => {
console.log(`childNode: ${childNode.key}`);
});
});

我如何遍历每个 child 及其 child ?我是否使用递归循环?

最佳答案

您可以使用一个函数,该函数获取实际级别并返回数组方法的回调。

在内部,回调显示键并再次调用该函数,并为下一次迭代增加级别。

function iter(level) {
return function (node) {
console.log('node', level, node.key);
(node.children || []).forEach(iter(level + 1));
};
}

var tree = [{ key: "parent1", id: "001", children: [{ key: "B", id: "002", children: [{ key: "C", id: "003", children: [{ key: "D", id: "004", children: [] }] }] }] }, { key: "parent2", id: "002", children: [{ key: "B", id: "002", children: [{ key: "C", id: "003", children: [{ key: "D", id: "004", children: [] }] }] }] }];

tree.forEach(iter(0));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 递归循环对象树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876030/

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