Convert JavaScript string in dot notation into an object reference

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

    Few years later, I found this that handles scope and array. e.g. a['b']["c"].d.etc

    function getScopedObj(scope, str) {
      let obj=scope, arr;
    
      try {
        arr = str.split(/[\[\]\.]/) // split by [,],.
          .filter(el => el)             // filter out empty one
          .map(el => el.replace(/^['"]+|['"]+$/g, '')); // remove string quotation
        arr.forEach(el => obj = obj[el])
      } catch(e) {
        obj = undefined;
      }
    
      return obj;
    }
    
    window.a = {b: {c: {d: {etc: 'success'}}}}
    
    getScopedObj(window, `a.b.c.d.etc`)             // success
    getScopedObj(window, `a['b']["c"].d.etc`)       // success
    getScopedObj(window, `a['INVALID']["c"].d.etc`) // undefined
    

提交回复
热议问题