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
.
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
.
Purely natively, I don't think so.
undefined
isn't extensible or changeable and that's about the only way I could imagine doing it without passing it through a function.You can't do it exactly with the syntax you want. But as usual, in JS you can write your own function:
so now you can do this:
without worrying if
bar
orbaz
are defined. If you don't like the[..]
in the function call you can always iterate over thearguments
object.Or you can use an eval-based solution. It's ugly, not recommended.
I had a desire to do this, so I wrote a package to handle it.
It'll even do arrays with numeric subscripts:
@slebetman's code doesn't seem to work. The last key should not be assigned an empty object, but rather the
val
. This code worked: