I have the objects tree, and i can\'t found all parents for concrete object id. Imagine i need to add some new field to each parent for object with id = 5. Can someone help
A recursion function isn't that difficult. Remember that you pass the new level onto the function if your parameter isn't met.
var tree = [{
id: 1,
children: [{
id: 3,
parentId: 1,
children: [{
id: 5,
parentId: 3,
children: [{
id: 6,
parentId: 5,
children: [{
id: 5,
parentId: 3,
children: []
}]
}]
}]
}]
}]; //wrap first obj in an array too.
searchTree(tree, 5);
console.log(tree);
function searchTree(tree, nodeId) {
for (let i = 0; i < tree.length; i++) {
if (tree[i].id == nodeId) {
tree[i]; //id found, now add what you need.
tree[i].newField = "added";
}//if child has children of its own, continu digging.
if (tree[i].children != null && tree[i].children.length > 0) {
searchTree(tree[i].children, nodeId); //pass the original nodeId and if children are present pass the children array to the function.
}
}
}