js 对 tree 递归遍历
无限嵌套的 tree
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: [] }]}], }]
},
]
,普通方法 只能遍历 两层
tree.map((parentNode) => {
console.log(`parentNode: ${parentNode.key}`);
const childrenNode = parentNode.children;
childrenNode.map((childNode) => {
console.log(`childNode: ${childNode.key}`);
});
});
使用 递归
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));
结果
node 0 parent1
node 1 B
node 2 C
node 3 D
node 0 parent2
node 1 B
node 2 C
node 3 D