Is there anyway, either natively or through a library, to use autovivification on Javascript objects?
IE, assuming foo
is an object with no properties, being able to just do foo.bar.baz = 5
rather than needing foo.bar = {}; foo.bar.baz = 5
.
You can't do it exactly with the syntax you want. But as usual, in JS you can write your own function:
function set (obj,keys,val) {
for (var i=0;i<keys.length;i++) {
var k = keys[i];
if (typeof obj[k] == 'undefined') {
obj[k] = {};
}
obj = obj[k];
}
obj = val;
}
so now you can do this:
// as per you example:
set(foo,['bar','baz'],5);
without worrying if bar
or baz
are defined. If you don't like the [..]
in the function call you can always iterate over the arguments
object.