Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 205
ben Avatar asked Dec 28 '22 15:12

ben


1 Answers

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
like image 68
Cristian Sanchez Avatar answered Dec 31 '22 15:12

Cristian Sanchez