Convert JavaScript string in dot notation into an object reference

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

    Using object-scan seems a bit overkill, but you can simply do

    const objectScan = require('object-scan');
    
    const get = (obj, p) => objectScan([p], { abort: true, rtn: 'value' })(obj);
    
    const obj = { a: { b: '1', c: '2' } };
    
    console.log(get(obj, 'a.b'));
    // => 1
    
    console.log(get(obj, '*.c'));
    // => 2
    

    There are a lot more advanced examples in the readme.

提交回复
热议问题