本文介绍了递归循环对象树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有树对象:
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级:
I want to loop through the tree but I only getting 2 levels down:
tree.map((parentNode) => { console.log(`parentNode: ${parentNode.key}`); const childrenNode = parentNode.children; childrenNode.map((childNode) => { console.log(`childNode: ${childNode.key}`); }); });如何通过每个孩子及其子女?我是否使用递归循环?
How do I go through every child and its children? Do I use recursive looping?
推荐答案您可以使用一个获取实际级别的函数并返回数组方法的回调。
You could use a function which takes the actual level and returns the callback for the array method.
在内部,回调显示键并再次调用该函数,下一次迭代的级别增加。
Inside, the callback displays the key and call the function again with an increased level for next iteration.
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; }
更多推荐
递归循环对象树
发布评论