Convert JavaScript string in dot notation into an object reference

前端 未结 27 3018
梦如初夏
梦如初夏 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:33

    A little more involved example with recursion.

    function recompose(obj,string){
        var parts = string.split('.');
        var newObj = obj[parts[0]];
        if(parts[1]){
            parts.splice(0,1);
            var newString = parts.join('.');
            return recompose(newObj,newString);
        }
        return newObj;
    }
    
    
    var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};
    
    alert(recompose(obj,'a.d.a.b')); //blah
    

提交回复
热议问题