4👍
✅
We can recursively search all nodes until we find the match:
getItemRow(id){
return findNodeWithId(id, this.parents)
}
findNodeWithId(id, rootArr) {
for (let el of rootArr) {
if (el.id === id) {
return el
}
if (el.children) {
const idFoundInChildren = findNodeWithId(id, el.children)
if (idFoundInChildren !== null) {
return idFoundInChildren
}
}
}
return null
}
1👍
You could take a recursion and find the object directly or by searching the children array.
const
find = (array, id) => {
let result;
array.some(o => result = o.id === id
? o
: find(o.children || [], id)
)
return result;
},
data = [{ id: 1, name: "parent 1" }, { id: 2, name: " parent 2", children: [{ id: 5, name: "parent-children 5" }, { id: 6, name: "parent-children 6", children: [{ id: 7, name: "parent-children-children 7" }, { id: 8, name: "parent-children-children 8", children: [{ id: 9, name: "parent-children-children-children 9" }, { id: 10, name: "parent-children-children-children 10" }] }] }] }, { id: 3, name: "parent 3" }, { id: 4, name: "parent 4" }];
console.log(find(data, 9));
Source:stackexchange.com