Convert JavaScript string in dot notation into an object reference

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

    you could also use lodash.get

    You just install this package (npm i --save lodash.get) and then use it like this:

    const get = require('lodash.get');
    
    const myObj = { user: { firstName: 'Stacky', lastName: 'Overflowy' }, id: 123 };
    
    console.log(get(myObj, 'user.firstName')); // prints Stacky
    console.log(get(myObj, 'id')); //prints  123
    
    //You can also update values
    get(myObj, 'user').firstName = John;
    

提交回复
热议问题