javascript - 递归循环对象树

标签 javascript arrays ecmascript-6

我有树对象:

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/

相关文章:

javascript - 如何在没有 module.exports 的情况下在 Javascript 中导出 ES6 类

javascript - react native 平面列表,从状态中删除元素时无法正确更新

javascript - 为什么在 JavaScript 数组方法中绑定(bind)回调比使用 thisArg 更好?

c - C 中 "strings"的数组

javascript - 排列需要帮助编码

javascript - 这不会访问 http 响应对象 :property does not exist on type Object

javascript - 如何在 PhantomJS 中测试 String.prototype.includes

javascript - Extjs 4.0.2a 打破网格列隐藏?

javascript - 如何在 Jasmine 测试中放入调试器?

javascript - 如何从数组中删除特定项目?