Suppose we are only given
var obj = {};
var propName = \"foo.bar.foobar\";
How can we set the prop
No recursions or callbacks overhead.
function setDeepVal(obj, path, val) {
var props = path.split('.');
for (var i = 0, n = props.length - 1; i < n; ++i) {
obj = obj[props[i]] = obj[props[i]] || {};
}
obj[props[i]] = val;
return obj;
}
// TEST
var obj = { hello : 'world' };
setDeepVal(obj, 'foo.bar.baz', 1);
setDeepVal(obj, 'foo.bar2.baz2', 2);
console.log(obj);