Convert JavaScript string in dot notation into an object reference

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

    Note if you're already using Lodash you can use the property or get functions:

    var obj = { a: { b: '1', c: '2' } };
    _.property('a.b')(obj); // => 1
    _.get(obj, 'a.b'); // => 1
    

    Underscore also has a property function but it doesn't support dot notation.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 05:58

    You can obtain value of an object member by dot notation with a single line of code:

    new Function('_', 'return _.' + path)(obj);
    

    In you case:

    var obj = { a: { b: '1', c: '2' } }
    var val = new Function('_', 'return _.a.b')(obj);
    

    To make it simple you may write a function like this:

    function objGet(obj, path){
        return new Function('_', 'return _.' + path)(obj);
    }
    

    Explanation:

    The Function constructor creates a new Function object. In JavaScript every function is actually a Function object. Syntax to create a function explicitly with Function constructor is:

    new Function ([arg1[, arg2[, ...argN]],] functionBody)
    

    where arguments(arg1 to argN) must be a string that corresponds to a valid javaScript identifier and functionBody is a string containing the javaScript statements comprising the function definition.

    In our case we take the advantage of string function body to retrieve object member with dot notation.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题