Convert JavaScript string in dot notation into an object reference

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

    here's my 10 cents to case, bellow function will get/set based on path provided,.. sure u can improve it, remove || and replace it with Object.hasOwnProperty if you do care about false values mistakenly,

    i tested it with a.b.c and a.b.2.c {a:{b:[0,1,{c:7}]}} and its works for both setting and getting :).

    cheerz

    function helper(obj, path, setValue){
      const l = String(path).split('.');
      return l.reduce((o,i, idx)=>{
       if( l.length-idx===1)  { o[i] = setValue || o[i];return setValue ? obj : o[i];}
      o[i] = o[i] || {};
       return o[i];
      }, x)
    }
    

提交回复
热议问题