Thabo
Thabo

Reputation: 1475

Loop over children of nodes recursively

I have a challenge looping over an array's objects that have nested children properties, the structure is like so

The traversing I have tried is not even close, I actually want the results to be an array that is flat

[{
element: 'a',
key: 'a',
isCollapsible: true,
isClickable: false,
children: [{
  element: 'a-1',
  key: 'a-1',
  indentChildren: false,
  children: [{
    element: 'a-1-1',
    key: 'a-1-1',
    children: [],
  }, {
    element: 'a-1-2',
    key: 'a-1-2',
    children: [],
  }],
}, {
  element: 'a-2',
  key: 'a-2',
  indentChildren: false,
  children: [{
    element: 'a-2-1',
    key: 'a-2-1',
    indentChildren: false,
    children: [{
      element: 'a-2-1-1',
      key: 'a-2-1-1',
      children: [],
    }],
  }, {
    element: 'a-2-2',
    key: 'a-2-2',
    children: [],
  }, {
    element: 'a-2-3',
    key: 'a-2-3',
    children: [],
  }],
}],
}]

Upvotes: 4

Views: 821

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

Since ES6 you might use a generator with nested yield to flatten the iteration:

 function* flatten(array){
   for(const el of array){
     yield el;
     yield* flatten(el.children);
   }
}

So you can do:

 for(const el of flatten(yourdata)){
    //...
 }

Upvotes: 3

Related Questions