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
.
The JavaScript language does not have a standard library. As a result new functionality is added to the global object, or developers find and adopt libraries that they bundle with the rest of their application.
JavaScript has several "top-level" built-in functions. JavaScript also has four built-in objects: Array, Date, Math, and String. Each object has special-purpose properties and methods associated with it. JavaScript also has constructors for Boolean and Number types.
Data Types in JavaScriptObject, Array, and Function (which are all types of objects) are composite data types. Whereas Undefined and Null are special data types.
Types of data that can be stored as a JSON string Primitive data types like numbers, booleans, and strings are JSON-safe, while values like functions, undefined, symbols, date-objects are not JSON-safe.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With