I have a multidimensional array representing a potentially unlimited deep category tree menu which looks like this
this.tree = [{
"title": "1. dragon-breath",
"items": []
}, {
"title": "2. moiré-vision",
"items": [{
"title": "2.1. tofu-animation",
"items": [{
"title": "2.1.1. spooky-giraffe",
"items": []
}, {
"title": "2.1.2. bubble-burst",
"items": []
}],
}, {
"title": "2.2. barehand-atomsplitting",
"items": []
}],
}, {
"title": "3. unicorn-zapper",
"items": []
}, {
"title": "4. romantic-transclusion",
"items": []
}];
and then I have an array path to one of tree leaves, that dynamically changes in time and can look like this
var path = [0]
next time it can look like this
var path = [1][1]
or this
var path = [1][0][1]
Now I need to change the title attribute of leave represented by this path. I cant find any decent way how to do it. Only thing, that came on my mind was eval function,
eval('tree'+getStringPathByArrayPath([1,0,1])+'.name = "'+updatedName+'"')
which I find kind of evil and also I am using this function as angular ng-model (getter/setter) so I dont want browser to evaluate this over and over.
Is there any decent way how to solve this or do I have a bad approach to this problematic?
PS: I cant just iterate over the path array recursively and get to the right tree leave node by node, because there is no passing by reference and every time I assign one subnode to variable, I get a copy (but I need to change the original).
Thanks for your time.
Although Javascript is pass-by-value, the value of any variable holding an object is a reference to the object. Passing such a variable will pass the reference, not a copy of the object. So this will change your tree:
var node = this.tree[path[0]];
for (var i = 1 ; i < path.length ; i++) {
node = node.items[path[i]];
}
node.title = updatedName;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments