Given a JS object
var obj = { a: { b: \'1\', c: \'2\' } }
and a string
\"a.b\"
how can I convert the stri
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;
};