JSFiddle - React, Tailwind, and code Playground
JavaScript
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 updateObject(data, path, value) {
var pathArray = path.split(">");
var pointer = data; // points to the current nested object
for (var i = 0, len = pathArray.length; i < len; i++) {
var path = pathArray[i];
if (pointer.hasOwnProperty(path)) {
if (i === len - 1) {
pointer[path] = value;
} else {
pointer = pointer[path];
}
} else {
// throw error or terminate. The path is incorrect
}
}
}
updateObject(data, path, "10.00");
console.log(data)