My path are like below in my tree structure :
Node : /myPath/Node
Node-1 : /myPath/Node/Node-1
Node-1-1 : /myPath/Node/Node-1-1
Now if my current object record from Node then from that node I would like to travel every child nodes of it and replace Node with First.
Expected output will be :
Node : /myPath/First
Node-1 : /myPath/First/Node-1
Node-1-1 : /myPath/First/Node-1-1
With my current code problem is it is only replacing search term(First) at first node but not for each of the child node.
var currentObj = { "name": "Node", "nodes": [ { "name": "Node-1", "nodes": [ { "name": "Node-1-1", "nodes": [ { "name": "Node-1-1-1", "nodes": [ ], "path": "/myPath/Node/Node-1/Node-1-1/Node-1-1-1" } ], "path": "/myPath/Node/Node-1/Node-1-1" } ], "path": "/myPath/Node/Node-1" } ], "path": "/myPath/Node" }; recursive(currentObj,"First"); console.log(currentObj); function recursive(node,replace) { console.log(node.path); node.path = replaceAll(node.path,'Node',replace); } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, "\\\\$1"); }
Recursively calling recursive
for each node in nodes
seems to work:
function recursive(node)
{
node.path = replaceAll(node.path,'Node','First');
node.nodes.forEach(recursive);
}
With extra arguments:
node.nodes.forEach(function(child_node) {
recursive(child_node, arg1, arg2);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.