Convert JavaScript string in dot notation into an object reference

前端 未结 27 3080
梦如初夏
梦如初夏 2020-11-21 05:09

Given a JS object

var obj = { a: { b: \'1\', c: \'2\' } }

and a string

\"a.b\"

how can I convert the stri

27条回答
  •  醉酒成梦
    2020-11-21 05:43

    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.

提交回复
热议问题