Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a library to support autovivification on Javascript objects?

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.

like image 539
James McMahon Avatar asked Nov 21 '12 17:11

James McMahon


People also ask

Is there a JavaScript standard library?

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.

Is number a built-in object in JavaScript?

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.

What are three types of objects supported by JavaScript?

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.

What can be stored in a JavaScript object?

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.


2 Answers

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.

like image 52
slebetman Avatar answered Nov 03 '22 01:11

slebetman


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.

like image 27
Snuffleupagus Avatar answered Nov 03 '22 01:11

Snuffleupagus