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

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

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

{
    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 :

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