It's slightly confusing that you've called your object data
but that data
is also an argument of your function. I've changed the argument's name therefore to newVal
in order to clear up this potential problem.
This loops through the path and constantly resets a variable called e
which starts by pointing to the data
object generally and gets more specific as we loop. At the end, you should have an almost reference to the exact property -- we use the last part of the path to set the new value.
function updateObject(newVal, path) {
var pathArray = path.split(">"),
i = 0,
p = pathArray.length - 1, // one short of the full path
e = data; // "import" object for changing (i.e., create local ref to it)
for (i; i < p; i += 1) { // loop through path
if (e.hasOwnProperty(pathArray[i])) { // check property exists
e = e[pathArray[i]]; // update e reference point
}
}
e[pathArray[i]] = newVal; // change the property at the location specified by path to the new value
};
You might need to add something to catch errors. I have put a check in with the hasOwnProperty()
call but you might need something more elaborate than this.
UPDATE
Had made a silly mistake in the code before but it should be working now. As evidenced here.