Convert JavaScript string in dot notation into an object reference

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

    Here is my implementation

    Implementation 1

    Object.prototype.access = function() {
        var ele = this[arguments[0]];
        if(arguments.length === 1) return ele;
        return ele.access.apply(ele, [].slice.call(arguments, 1));
    }
    

    Implementation 2 (using array reduce instead of slice)

    Object.prototype.access = function() {
        var self = this;
        return [].reduce.call(arguments,function(prev,cur) {
            return prev[cur];
        }, self);
    }
    

    Examples:

    var myobj = {'a':{'b':{'c':{'d':'abcd','e':[11,22,33]}}}};
    
    myobj.access('a','b','c'); // returns: {'d':'abcd', e:[0,1,2,3]}
    myobj.a.b.access('c','d'); // returns: 'abcd'
    myobj.access('a','b','c','e',0); // returns: 11
    

    it can also handle objects inside arrays as for

    var myobj2 = {'a': {'b':[{'c':'ab0c'},{'d':'ab1d'}]}}
    myobj2.access('a','b','1','d'); // returns: 'ab1d'
    

提交回复
热议问题