I note the following similarity to this post: Dynamic deep setting for a JavaScript object
However, the above post is based upon a known structure and depth to the javascript object and not truly dynamic. Truly dynamic would suggest that you did not have any precursor knowledge of the structure, just a path and a value to replace it with. I have created a fairly good use case over on JSFiddle here:
http://jsfiddle.net/kstubs/nJrLp/1/
function Message(message) {
$('result').insert('<div>' + message + '</div>');
}
var obj = {
"array": [1, 2, 3],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f",
"complex_array1": [{
"g": "h"
}, {
"bingo": "bongo"
}, {
"x": {
"complex_array2": [{
"h": "i"
}, {
"j": "k"
}, {
"bingo": "bongo"
}, {
"bango": "jango"
}]
}
}]
},
"string": "Hello World"
};
var list = [{
"h": "i"
}, {
"j": "k"
}];
function walk(path,value) {
var a = path.split('.');
var context = obj;
for (i = 0; i < a.size(); i++) {
context = context[a[i]];
}
}
The use case:
- Find complex_array2
- Update its list to a new list (a new array)
The new array is the array list which should replace the list for complex_array2. The javascript function walk does just that, walks the javascript object until the path criteria is met and then sets the value to whatever value is passed to the walk function, however the new value does not stick.
I know why it doesn't stick, because as you walk over an object of type array you lose the pointer to the original object. So, the challenge is to walk the javascript object and not lose context of the original object.
Thanks for any assistance.
Karl..