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);
}
}