Created
October 17, 2014 15:41
-
-
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.
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
_.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