JSFiddle - React, Tailwind, and code Playground

by guypursey

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(obj, path, val) {
    var pathArray = path.split(">"),
        i = 0,
        p = pathArray.length - 1,
        e = obj; // "import" object for changing (i.e., create local ref to it)
    console.log(e);
    for (i; i < p; i += 1) { // loop through path
        console.log(i, pathArray[i]);
        if (e.hasOwnProperty(pathArray[i])) { // check property exists
            e = e[pathArray[i]]; // update e reference point
            console.log(e);
        }
    }
    e[pathArray[i]] = val; // change the property at the location specified by path to the new value
};
updateObject(data, path, "10.00");

console.log(data)