I have a complex array of objects where each object may contain nested children.
For example:
const data = [
{
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: 2,
name: 'c1',
children: [],
},
],
},
{ id: 3, name: 'parent 3', children: [] },
];
If I search for the ID 'g1', I want to get the result:
const result = ['parent 1', 'child 1', 'grand 1']
The loop should stop and return all the names it passed through until the condition (ID) is met.
Current Approach Implemented:
/**
* Details
* @param id the value you are searching for
* @param items nested array of objects containing children
* @param key name of the value being searched for
* @returns an array of strings that match the id
* @example ['parent 1', 'child 1', 'grand 1']
*/
export function findAll(id: string, items: any, key: string): string[] {
let i = 0;
let found;
let result = [];
for (; i < items.length; i++) {
if (items[i].id === id) {
result.push(items[i][key]);
} else if (_.isArray(items[i].children)) {
found = findAll(id, items[i].children, key);
if (found.length) {
result = result.concat(found);
}
}
}
return result;
}