Convert JavaScript string in dot notation into an object reference

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

    Other proposals are a little cryptic, so I thought I'd contribute:

    Object.prop = function(obj, prop, val){
        var props = prop.split('.')
          , final = props.pop(), p 
        while(p = props.shift()){
            if (typeof obj[p] === 'undefined')
                return undefined;
            obj = obj[p]
        }
        return val ? (obj[final] = val) : obj[final]
    }
    
    var obj = { a: { b: '1', c: '2' } }
    
    // get
    console.log(Object.prop(obj, 'a.c')) // -> 2
    // set
    Object.prop(obj, 'a.c', function(){})
    console.log(obj) // -> { a: { b: '1', c: [Function] } }
    

提交回复
热议问题