Convert JavaScript string in dot notation into an object reference

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

    Yes, it was asked 4 years ago and yes, extending base prototypes is not usually good idea but, if you keep all extensions in one place, they might be useful.
    So, here is my way to do this.

       Object.defineProperty(Object.prototype, "getNestedProperty", {
        value     : function (propertyName) {
            var result = this;
            var arr = propertyName.split(".");
    
            while (arr.length && result) {
                result = result[arr.shift()];
            }
    
            return result;
        },
        enumerable: false
    });
    

    Now you will be able to get nested property everywhere without importing module with function or copy/pasting function.

    UPD.Example:

    {a:{b:11}}.getNestedProperty('a.b'); //returns 11
    

    UPD 2. Next extension brokes mongoose in my project. Also I've read that it might broke jquery. So, never do it in next way

     Object.prototype.getNestedProperty = function (propertyName) {
        var result = this;
        var arr = propertyName.split(".");
    
        while (arr.length && result) {
            result = result[arr.shift()];
        }
    
        return result;
    };
    

提交回复
热议问题