Convert JavaScript string in dot notation into an object reference

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

    You can use the library available at npm, which simplifies this process. https://www.npmjs.com/package/dot-object

     var dot = require('dot-object');
    
    var obj = {
     some: {
       nested: {
         value: 'Hi there!'
       }
     }
    };
    
    var val = dot.pick('some.nested.value', obj);
    console.log(val);
    
    // Result: Hi there!
    

提交回复
热议问题