4

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?

3
  • map? do you need to return the result somewhere? Commented Jun 15, 2018 at 12:53
  • Yes and I dont always know how many levels it have, sometimes it have 2 and sometimes it have 5 Commented Jun 15, 2018 at 12:55
  • i think you will have to use recursion Commented Jun 15, 2018 at 12:56

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate over the array recursively like this:

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

function iterator(tree) {
  tree.forEach((parentNode) => {
    console.log(`Node: ${parentNode.key}`);
    if (parentNode.hasOwnProperty('children')) iterator(parentNode.children)       
  });
}

iterator(tree)

Comments

0

What about:

const process = (level = 0) => (parentNode) => {
  console.log(`${level} parentNode: ${parentNode.key}`);
  if (parentNode.children && level < 2) {
    parentNode.children.forEach(process(level + 1));
  }
}

tree.forEach(process());

Comments

0

Yes, you can trace it easily with recursive function.

For example like this:

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

function goThrough(node, parent = null) {
  if (!node) {
    return;
  }
  node.map((parentNode) => {
    console.log(`node: ${parentNode.key}, parent: ${parent}`);
    goThrough(parentNode.children, parentNode.key);    
  });
}

goThrough(tree);

Comments

0
function printKey(obj){
    obj.map(x=>{
    console.log(x.key);
    if (x.hasOwnProperty('children')){
    printChild(x.children);
    }
  });
}

3 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
i will keep it in mind while answering in future. i am new to this platform & do not have much experience but i am sure this advice will help me write better answers in future. Thank you guys for advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.