For an object of this structure:
const myObj = {
id: 1,
name: '1',
children: [
{
id: 2,
name: '2',
children: [
{
id: 3,
name: '3',
children: []
}
]
},
{
id: 4,
name: '4',
children: [
{
id: 5,
name: '5',
children: [
{
id: 6,
name: '6',
children: [
{
id: 7,
name: '7',
children: []
}
]
}
]
}
]
},
]
}
How would I get an object by value (id)? So I'm looking for a function where if I call this:
findObj(myObj, 6);
It would return this:
{
id: 6,
name: '6',
children: [
{
id: 7,
name: '7',
children: []
}
]
}
Another example:
findObj(myObj, 3);
Would return this:
{
id: 3,
name: '3',
children: []
}
I know I need a recursion function. Heres what I have so far:
findObj(obj, id) {
if (obj.id === id) {
return obj;
}
obj.forEach(x => {
if (x.id === id) {
return x;
} else {
this.findObj(x.children, id);
}
});
}
(This is in an angular class)