Convert JavaScript string in dot notation into an object reference

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

    Note if you're already using Lodash you can use the property or get functions:

    var obj = { a: { b: '1', c: '2' } };
    _.property('a.b')(obj); // => 1
    _.get(obj, 'a.b'); // => 1
    

    Underscore also has a property function but it doesn't support dot notation.

提交回复
热议问题