Automatically create object if undefined

后端 未结 12 1034
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:45

    I've made some changes on columbus's answer to allow create arrays:

    function addProps(obj, arr, val) {
    
      if (typeof arr == 'string')
        arr = arr.split(".");
    
      var tmpObj, isArray = /^(.*)\[(\d+)\]$/.exec(arr[0])
      if (isArray && !Number.isNaN(isArray[2])) {
        obj[isArray[1]] = obj[isArray[1]] || [];
        obj[isArray[1]][isArray[2]] = obj[isArray[1]][isArray[2]] || {}
        tmpObj = obj[isArray[1]][isArray[2]];
      } else {
        obj[arr[0]] = obj[arr[0]] || {};
        tmpObj = obj[arr[0]];
      }
    
      if (arr.length > 1) {
        arr.shift();
        addProps(tmpObj, arr, val);
      } else
        obj[arr[0]] = val;
    
      return obj;
    
    }
    
    
    var myObj = {}
    addProps(myObj, 'sub1[0].sub2.propA', 1)
    addProps(myObj, 'sub1[1].sub2.propA', 2)
    
    console.log(myObj)

    I think that is possible to allow use "sub1[].sub2..." to just push into the sub1 array, instead of specify the index, but that's enough for me now.

提交回复
热议问题