Convert JavaScript string in dot notation into an object reference

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

    Here is my code without using eval. Its easy to understand too.

    function value(obj, props) {
      if (!props) return obj;
      var propsArr = props.split('.');
      var prop = propsArr.splice(0, 1);
      return value(obj[prop], propsArr.join('.'));
    }
    
    var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};
    
    console.log(value(obj, 'a.d.a.b')); //returns blah
    

提交回复
热议问题