开发者

js build object path in property assignment

开发者 https://www.devze.com 2023-03-28 11:34 出处:网络
is there a way to automatically create subobjects in an assignment after construction, i.e. var obj = {};

is there a way to automatically create subobjects in an assignment after construction, i.e.

var obj = {};
obj.a.b.c=13;

the above gives me a "obj.a is undefined" error

i wrote a function to do this, but wond开发者_StackOverflow中文版ered if there was an easier way

_setObjectProperty(obj,13,['a','b','c']);
function _setObjectProperty(obj,value,loc)
{
    if(loc.length>1) {
        obj[loc[0]] = obj[loc[0]] || {};
        _setObjectProperty(obj[loc[0]],value,loc.splice(1));
    }
    else if(loc.length===1) {
        obj[loc[0]]=value;
    }
}


No, there's no built in way to do this in JavaScript. The only way is to create your own function like you did. If you want the convenience of the dot operator/notation you can use the following function:

var set = function(path, value, root) {
  var segments = path.split('.'),
      cursor = root || window,
      segment,
      i;

  for (i = 0; i < segments.length - 1; ++i) {
     segment = segments[i];
     cursor = cursor[segment] = cursor[segment] || {};
  }

  return cursor[segments[i]] = value;
};

set("a.b.c", 2);

console.log(a.b.c) // => 2
0

精彩评论

暂无评论...
验证码 换一张
取 消