ben
ben

Reputation: 43

js build object path in property assignment

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 wondered 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;
    }
}

Upvotes: 4

Views: 3813

Answers (1)

Cristian Sanchez
Cristian Sanchez

Reputation: 32117

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

Upvotes: 12

Related Questions