'How to build an object of nested elements from a list?

From a list of objects, I try to create a nested elements object from

The list is as follows

[              
  { 
    label: 'Root',
    data: 173,            
    children: [],  
  },           
  {
    label: 'Root child 1',
    data: 174,                                                                                                                                                        
    children: [],
  },
  {
    label: 'Root child 2',
    data: 175,
    children: [],
  },
  {
    label: 'Root child 3',
    data: 176,
    children: [],
  }
]

And I want to turn it into

{
    label: 'Root',
    data: 173,
    children: [
      {
        label: 'Root child 1',
        data: 174,
        children: [
          {
            label: 'Root child 2',
            data: 175,
            children: [
              {
                label: 'Root child 3',
                data: 176,
                children: [ ],
              }
            ],
          }
        ],
      }
    ],
  }

The logic is that each list item from top to bottom will hold the next item in the children property. This, until there is something to add

The list can have a single element or an undefined number

I wanted to add something that I have tried but I feel long to solve it



Solution 1:[1]

you can use reduceRight for that

it's like reduce but it goes right to left instead of left to right

const data = [              
  { 
    label: 'Root',
    data: 173,            
    children: [],  
  },           
  {
    label: 'Root child 1',
    data: 174,                                                                                                                                                        
    children: [],
  },
  {
    label: 'Root child 2',
    data: 175,
    children: [],
  },
  {
    label: 'Root child 3',
    data: 176,
    children: [],
  }
]

const result = data.reduceRight((res, item) => {
  return {
    ...item,
    children: [res]
  }
})



console.log(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R4ncid