[javascript] Convert JavaScript string in dot notation into an object reference

var a = { b: { c: 9 } };

function value(layer, path, value) {
    var i = 0,
        path = path.split('.');

    for (; i < path.length; i++)
        if (value != null && i + 1 === path.length)
            layer[path[i]] = value;
        layer = layer[path[i]];

    return layer;
};

value(a, 'b.c'); // 9

value(a, 'b.c', 4);

value(a, 'b.c'); // 4

This is a lot of code when compared to the much simpler eval way of doing it, but like Simon Willison says, you should never use eval.

Also, JSFiddle.