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

64
Vistas
Recursive function for getting last children in hierarchy array of objects

I need a little help here. I have a hierarchical array of objects.
And the purpose is to get always the last children of the objects.

testData = [
    {
        id: 1,
        name: 'parent 1',
        children: [
            {
                id: 'c1',
                name: 'child 1',
                children: [
                    {
                        id: 'g1',
                        name: 'grand 1',
                        children: [],
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        name: 'parent 2',
        children: [
            {
                id: 'c2',
                name: 'child 2',
                children: [
                    {
                        id: 'g2',
                        name: 'grand2',
                        children: [],

                    },
                    {
                        id: 'g21',
                        name: 'grand21',
                        children: [],

                    },
                ],
            },
        ],
    },
]

For example, if i send:

id:1 => it must send object with id:'g1' back.
id:c2 => it must send object with id:'g2' & id:'g21' back.
id: g2 => it must send object with id:'g2' back.

Any help will be much appreciated! Thx!

Edit:

I'm trying to do something like this:

function getChildren(data: Array<any>, value: any, newArray?: Array<any>) {
  if (data !== undefined)
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      if (element['id'] === value && element.children)
        getChildren(element['children'], value, newArray);
      if (element['id'] === value && !element.children) newArray?.push(element);
    }
}
about 4 years ago · Juan Pablo Isaza
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