Automatically create object if undefined

后端 未结 12 1055
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 14:01

    New object

    myObj = {};
    

    recursive function

    function addProps(obj, arr, val) {
    
        if (typeof arr == 'string')
            arr = arr.split(".");
    
        obj[arr[0]] = obj[arr[0]] || {};
    
        var tmpObj = obj[arr[0]];
    
        if (arr.length > 1) {
            arr.shift();
            addProps(tmpObj, arr, val);
        }
        else
            obj[arr[0]] = val;
    
        return obj;
    
    }
    

    Call it with a dot notated string

    addProps(myObj, 'sub1.sub2.propA', 1);
    

    or with an array

    addProps(myObj, ['sub1', 'sub2', 'propA'], 1);
    

    and your object will look like this

    myObj = {
      "sub1": {
        "sub2": {
          "propA": 1
        }
      }
    };
    

    It works with non-empty objects too!

提交回复
热议问题