I would like to know what is the best way to update the member of the multilevel object collection in JavaScript
Here is the simplified version of my collection:
this.Steps = [
{ id: 1, text: "test", childSteps:
[
{ id: 2, text: "test"},
{ id: 3, text: "test"},
{ id: 4, text: "test", childSteps:
[
{ id: 10, text: "test"},
{ id: 11, text: "test"}
]}
},
{ id: 5, text: "test"},
{ id: 6, text: "test"},
{ id: 7, text: "test"},
{ id: 8, text: "test"},
{ id: 9, text: "test"}
]
}
];
The ideal would be to have a function to be called like:
updateObjectByID(11, 'string to be set');
This is easy to be done when we have only 1 level of objects. But when using recursion on multilevel collection its getting much harder.
I'm currently using a function that is parsing the whole collection and building string like :
this.Steps[0].childSteps[3].childSteps[1].text == "string to be set"
and then I do eval()
on that string.
I'm sure there might be a much cleaner solution.
Using eval is making my class impossible to compress btw.
Any help would be greatly appreciated.
Thanks in advance
You can build a map of objects by id for direct access:
A comment on your code: You overcomplified a lot. When the condition
if(obj.id == objId)
is met, you have yourobj
reference already!!! Now there is absolutely no need to search for a path to it, build a string from that, and eval it. Just assign directly to its property!You must recursively descend your tree structure searching for the object with the target "id" and replace its text. For example:
However, this solution can be optimized by tree pruning.
Since you call
updateObjectById()
with an ID, the ID has to be unique. Why don´t you change your structure like this then:This way you can easily update your entries like this:
With the extra attribute
parent
you can still easily get all the children of an element like this:Here is demo. http://jsfiddle.net/qDWX8/