Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

65
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda