-1

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

PeterKA
  • 24,158
  • 5
  • 26
  • 48
Czachovsky
  • 157
  • 2
  • 7
  • 1
    what have u tried so far – gil Apr 01 '22 at 15:39
  • Won't the name be `name2.2`? What is the problem you're trying to solve? – Andy Apr 01 '22 at 15:43
  • Does this answer your question? [Find by key deep in a nested array](https://stackoverflow.com/questions/15523514/find-by-key-deep-in-a-nested-array) – pilchard Apr 01 '22 at 15:47
  • also [How to find object with id value in deep nested array?](https://stackoverflow.com/questions/49308484/how-to-find-object-with-id-value-in-deep-nested-array) and [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – pilchard Apr 01 '22 at 15:48

1 Answers1

4

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)}
*/
Adrien De Peretti
  • 3,342
  • 16
  • 22