4

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

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

2 Comments

This is brilliant but how does it work exactly? I don't see where the root gets updated.
It seems that the root is the object were you may want to attach that path to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.