Last active
April 21, 2017 04:09
-
-
Save clarketm/7430a3bb742af51ec129e371d25651f0 to your computer and use it in GitHub Desktop.
Access nested JavaScript object value from string key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Access nested JavaScript object value from string key | |
* | |
* @memberof Object.prototype | |
* @param s {String} property string | |
* @return {String} value for property string | |
* | |
* [http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key] | |
*/ | |
Object.prototype.byString = function(s) { | |
s = s.replace(/\[(\w+)\]/, ".$1"); | |
s = s.replace(/^\./, ""); | |
var self = this, | |
a = s.split("."); | |
for (var i = 0; i < a.length; i++) { | |
var k = a[i]; | |
if (k in self) { | |
self = self[k]; | |
} else { | |
return; | |
} | |
} | |
return self; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment