Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive looping a object tree

I have tree object:

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: [] }]}], }] 
    },
]

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?


1 Answers

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; }
like image 183
Nina Scholz Avatar answered Oct 19 '25 04:10

Nina Scholz