Convert JavaScript string in dot notation into an object reference

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

    I suggest to split the path and iterate it and reduce the object you have. This proposal works with a default value for missing properties.

    const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);
    
    console.log(getValue({ a: { b: '1', c: '2' } }, 'a.b'));
    console.log(getValue({ a: { b: '1', c: '2' } }, 'foo.bar.baz'));

提交回复
热议问题