Convert JavaScript string in dot notation into an object reference

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

    GET / SET answer that also works in react native (you can't assign to Object.prototype currently):

    Object.defineProperty(Object.prototype, 'getNestedProp', {
        value: function(desc) {
            var obj = this;
            var arr = desc.split(".");
            while(arr.length && (obj = obj[arr.shift()]));
            return obj;
        },
        enumerable: false
    });
    
    Object.defineProperty(Object.prototype, 'setNestedProp', {
        value: function(desc, value) {
            var obj = this;
            var arr = desc.split(".");
            var last = arr.pop();
            while(arr.length && (obj = obj[arr.shift()]));
            obj[last] = value;
        },
        enumerable: false
    });
    

    Usage:

    var a = { values: [{ value: null }] };
    var b = { one: { two: 'foo' } };
    
    a.setNestedProp('values.0.value', b.getNestedProp('one.two'));
    console.log(a.values[0].value); // foo
    

提交回复
热议问题