Last active
August 29, 2015 14:21
-
-
Save shmaltorhbooks/6bfeb8a43e52adf01ebb to your computer and use it in GitHub Desktop.
Access to object members by string path
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
| /** | |
| * @example Object.byString(someObject, 'part1.name') | |
| * @example Object.byString(someObject, 'part2.qty') | |
| * @example Object.byString(someObject, 'part3[0].name') | |
| * | |
| * @param obj {Object} | |
| * @param str {String} | |
| * @returns {*} | |
| */ | |
| Object.byString = function(obj, str) { | |
| if (str in obj) { | |
| return obj[str]; | |
| } | |
| if (!(str.length) || (null === obj)) { | |
| return obj; | |
| } | |
| var a = str.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.'); // convert indexes to properties and strip a leading dot | |
| for (var i = 0, n = a.length; i < n; ++i) { | |
| var k = a[i]; | |
| if ((null !== obj) && (k in obj)) { | |
| obj = obj[k]; | |
| } else { | |
| return; | |
| } | |
| } | |
| return obj; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment