Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!