Automatically create object if undefined

后端 未结 12 1057
Happy的楠姐
Happy的楠姐 2020-12-07 13:07

Is there an easy way to automatically add properties to objects if they don\'t allready exist?

Consider the following example:

var test = {}
test.hel         


        
12条回答
  •  醉话见心
    2020-12-07 13:34

    You won't be able to do this without some sort of function, as JavaScript doesn't have a generic getter/setter method for objects (Python, for example, has __getattr__). Here's one way to do it:

    function add_property(object, key, value) {
        var keys = key.split('.');
    
        while (keys.length > 1) {
            var k = keys.shift();
    
            if (!object.hasOwnProperty(k)) {
                object[k] = {};
            }
    
            object = object[k];
        }
    
        object[keys[0]] = value;
    }
    

    If you really want to, you could add it to the prototype of Object. You can call it like so:

    > var o = {}
    > add_property(o, 'foo.bar.baz', 12)
    > o.foo.bar.baz
    12
    

提交回复
热议问题