Created
September 14, 2015 08:54
-
-
Save shmaltorhbooks/7de9a976ca248d5cdfcd to your computer and use it in GitHub Desktop.
access to object properties 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
| Object.path = Object.byString = function(obj, str, undefined) { | |
| 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 undefined; | |
| } | |
| } | |
| return obj; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment