I am trying to save path for each of the node by traversing from root node to the leaf node.
For example, I have nodes like this in hierarchical structure :
Node - 1
Node-1-1
Node-1-1-1
Expected output for each node:
So for Node - 1 I would like to have value in property path : /myPath/Node - 1
So for Node-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1
So for Node-1-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1/Node-1-1-1
But path I am getting is like below with my code for Node-1-1-1:
"/myPath/Node-1-1-1"
But expected out is like below :
/myPath/Node - 1/Node-1-1/Node-1-1-1 (becuase Node-1-1-1 belongs to Node-1-1 but Node-1-1 in turn belongs to Node - 1).
Demo:
var tree = JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');
traverseTree(tree);
console.log(tree);
function traverseTree(nodes)
{
nodes.forEach(function (node) {
node.path= getPath(node.name)
if (node.nodes) {
traverseTree(node.nodes);
}
});
}
function getPath(name)
{
var path = "/myPath/";
path = path + name;
return path;
}