Im trying to figure out if its possible to update a JavaScript object, using a string as the path.
In the example below, I'm trying to figure out how I can update the first books price using
store>book>0>price
as my path.
I know I can access this by writing data['store']['book'][0]['price']
but I need to be able to do this dynamically. Ive tried a few things but had no luck. Any Ideas?
This needs to work for any depth , not a fixed depth
Data:
var data = {
"store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
var path = "store>book>0>price"
Function:
function updateObject(object, path, data) {
var pathArray = path.split(">");
// Some code here
}
updateObject(data, path, "10.00");
Update
As felix pointed out the answer can be found here. Dynamic deep setting for a JavaScript object
Here is a working example for my scenario http://jsfiddle.net/blowsie/Sq8j3/9/