Convert JavaScript string in dot notation into an object reference

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

    I used this code in my project

    const getValue = (obj, arrPath) => (
      arrPath.reduce((x, y) => {
        if (y in x) return x[y]
        return {}
      }, obj)
    )
    

    Usage:

    const obj = { id: { user: { local: 104 } } }
    const path = [ 'id', 'user', 'local' ]
    getValue(obj, path) // return 104
    

提交回复
热议问题