Given a JS object
var obj = { a: { b: \'1\', c: \'2\' } }
and a string
\"a.b\"
how can I convert the stri
var a = { b: { c: 9 } };
function value(layer, path, value) {
var i = 0,
path = path.split('.');
for (; i < path.length; i++)
if (value != null && i + 1 === path.length)
layer[path[i]] = value;
layer = layer[path[i]];
return layer;
};
value(a, 'b.c'); // 9
value(a, 'b.c', 4);
value(a, 'b.c'); // 4
This is a lot of code when compared to the much simpler eval
way of doing it, but like Simon Willison says, you should never use eval.
Also, JSFiddle.