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

111
Views
Find deeply nested object by id

I need to find name in a deeply nested object by id. Maybe lodash will help? What is the cleanest way to do it, If I don't know how many nested object there will be in my array?

Here's example array:

let x = [
   {
        'id': '1',
        'name': 'name1',
        'children': []
    },
    {
        'id': '2',
        'name': 'name2',
        'children': [{
                'id': '2.1',
                'name': 'name2.1',
                'children': []
            },
            {
                'id': '2.2',
                'name': 'name2.2',
                'children': [{
                        'id': '2.2.1',
                        'name': 'name2.2.1'
                    },
                    {
                        'id': '2.2.2',
                        'name': 'name2.2.2'
                    }
                ]
            }
        ]
    },
    {
        'id': '3',
        'name': 'name3',
        'children': [{
                'id': '3.1',
                'name': 'name3.1',
                'children': []
            },
            {
                'id': '3.2',
                'name': 'name3.2',
                'children': []
            }
        ]
    }
];

For example I have id "2.2" and i need name of it. Thanks

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

0

from your data here is a solution that can help you achieve that easily

function findById(array, id) {
  for (const item of array) {
    if (item.id === id) return item;
    if (item.children?.length) {
      const innerResult = findById(item.children, id);
      if (innerResult) return innerResult;
    }
  }
}

const foundItem = findById(x, "2.2");
console.log(foundItem);
/*
    The result obtained here is: {id: '2.2', name: 'name2.2', children: Array(2)}
*/
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!