Q:

Create an object out of dot notation

This is a reverse question to this question.
Given an object x={a:1,b:2} and a string c.d=3, modify object x to the following:
{
  a:1,
  b:2,
  c:{
    d:3
  }
}

I'm looking for a solution that does not use eval. The use case is as follows:
x being a configuration object, we call:
config.set("music.shuffle",true)
Now, music.shuffle must be parsed somehow and added to the internal object x inside the config.set function, so that x looks something like:
x={a:1,b:2,music:{shuffle:true}}

A:

Off the top of my head I guess you can do something like this:
function addValueToObj(obj, newProp) {
    newProp = newProp.split("=");       // separate the "path" from the "value"

    var path = newProp[0].split("."),     // separate each step in the "path"
        val = newProp.slice(1).join("="); // allow for "=" in "value"

    for (var i = 0, tmp = obj; i < path.length - 1; i++) {
       tmp = tmp[path[i]] = {};     // loop through each part of the path adding to obj
    }
    tmp[path[i]] = val;             // at the end of the chain add the value in
}

var x = {a:1, b:2};
addValueToObj(x, "c.d=3");
// x is now {"a":1,"b":2,"c":{"d":"3"}}
addValueToObj(x, "e.f.g.h=9=9");
// x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}

Demo: http://jsfiddle.net/E8dMF/1/

A:

You can do this with lodash.set()

> l=require('lodash')
> x={a:1,b:2};
{ a: 1, b: 2 }
> l.set(x, 'c.d', 3)
{ a: 1, b: 2, c: { d: 3 } }

A:

I believe dojo's setObject does what you want. If you (understandably) don't want to pull in all of dojo then I would recommend examining their (freely available) source or loading just base (only 4k) via AMD. It looks something like this :
function setObject(name, value, context) {
    var parts=name.split("."), 
    p=parts.pop();
    for(var i=0, j; context && (j=parts[i]); i++){
        context = (j in context ? context[j] : context[j]={});
    }
    return context && p ? (context[p]=value) : undefined; // Object
}

So in your case you would do :
x={a:1,b:2};
setObject("c.d", 3, x);

Warning : unless you only ever deal with trivial cases, I would urge you to still go check out the full dojo implementation, which deals with cases where no context is provided etc.

