Modify A Javascript Object While Iterating Its Properties
Can javascript implement pass-by-reference techniques on function call? You see, I have the JSON below and I need to traverse all its node. While traversing, if the current item is
Solution 1:
Please check this one
var default_tree = [....] //Arrayfunctiontraverse(arrDefaultTree){
arrDefaultTree.forEach(function(val,key){
if(val.hasOwnProperty("nodes")){
val.isParent = true;
traverse(val.nodes);
}
})
}
traverse(default_tree);
console.log(default_tree);
Hope this helpful.
Solution 2:
With two functions, one that call then self. One find the nodes and the other one loop througgh the arrays.
traverseTree(default_tree);
functiontraverseTree (tree) {
var i = 0, len = tree.length;
for(;i < len; i++) {
var obj = tree[i];
findNodes(obj);
}
}
functionfindNodes (obj) {
var keys = Object.keys(obj);
if (keys.indexOf('nodes') > -1) {
obj.isParent = true;
traverseTree(obj.nodes);
}
}
Post a Comment for "Modify A Javascript Object While Iterating Its Properties"