递归循环对象树

编程入门 行业动态 更新时间:2024-10-28 17:27:54
本文介绍了递归循环对象树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有树对象:

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; }

更多推荐

递归循环对象树

本文发布于:2023-10-15 12:22:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!