Skip to content

Instantly share code, notes, and snippets.

@djmccormick
Created October 17, 2014 15:41
Show Gist options
  • Save djmccormick/b56ded1cdfa54dca6d7c to your computer and use it in GitHub Desktop.
Save djmccormick/b56ded1cdfa54dca6d7c to your computer and use it in GitHub Desktop.
Add to Underscore.js the ability to get a nested object property via a path string.
_.mixin({
/**
* getNestedObjectPropertyByPath
*
* Helps in accessing a nested object property via a path string
* See http://stackoverflow.com/a/6491621/679369
*
* @param {object} o An object
* @param {string} s A string representing the key of a property to return
* @return {*} The property of o represented by s
*/
getNestedObjectPropertyByPath: function (o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1');
s = s.replace(/^\./, '');
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (n in o) {
o = o[n];
} else {
return;
}
}
return o;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment