Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active April 21, 2017 04:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarketm/7430a3bb742af51ec129e371d25651f0 to your computer and use it in GitHub Desktop.
Save clarketm/7430a3bb742af51ec129e371d25651f0 to your computer and use it in GitHub Desktop.
Access nested JavaScript object value from string key
/**
* 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