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
The easiest solution is to flatten the tree structure down so you can just look up ids and do a simple while loop
var tree = {
id: 1,
children: [
{
id: 3,
parentId: 1,
children: [
{
id: 5,
parentId: 3,
children: []
}
]
}
]
}
// We will flatten it down to an object that just holds the id with the object
var lookup = {}
function mapIt (node) {
lookup[node.id] = node;
//recursive on all the children
node.children && node.children.forEach(mapIt);
}
mapIt(tree)
// This takes a node and loops over the lookup hash to get all of the ancestors
function findAncestors (nodeId) {
var ancestors = []
var parentId = lookup[nodeId] && lookup[nodeId].parentId
while(parentId !== undefined) {
ancestors.unshift(parentId)
parentId = lookup[parentId] && lookup[parentId].parentId
}
return ancestors;
}
// Let us see if it works
console.log("5: ", findAncestors(5))