Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda