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

Time:08-05

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 =)

CodePudding user response:

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

  • Related