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

63
Views
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
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!