Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting all the children of a tree javascript object as a flat array

I have a tree-based javascript object.

let tree = {
   id: 1, children: [
    {id: 2},
    {id: 3},
    {
     id: 4, children: [
      {id: 5},
      {id: 6},
      {
       id: 7, children: [
        {id: 8},
        {id: 9},
        {id: 10,}
       ]
      }
     ]
    }
   ]
  }

So, im trying to get all of them as a flat array, like this:

let flattenedTree = [
  { id: 1, children: [ /*All of it children...*/ ] },
  { id: 2 },
  { id: 3 },
  { id: 4, children: [ /*All of it children...*/ ] },
  { id: 5 },
  { id: 6 },
  { id: 7, children: [ /*All of it children...*/ ] },
  { id: 8 },
  { id: 9 },
  { id: 10 }
]

What options do i have to get them all without doing some dirty spaguetti code? I tried using array.forEach() but it naturally requires doing another iteration inside it, and surely will require it again while doing in this way, Thanks for the help =)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Recursion is the best choice to work with trees. It allows you to do this without spaghetti code:

function treeToList(tree) {
   const result = [];
   
   result.push(tree);
   const children = tree.children || [];
   children.forEach(child => {
     const childResult = treeToList(child);
     result.push(...childResult)
   })

   return result;
}

treeToList(tree)

Read more about recursion here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading