Last active
December 16, 2015 16:19
-
-
Save aaronmccall/5462344 to your computer and use it in GitHub Desktop.
Eliminates the need to do obj && obj.prop && obj.prop.subprop testing
This file contains 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
function resolver(prop_string, obj) { | |
if (!obj) return; | |
if (prop_string.indexOf('.') === -1) return obj[prop_string]; | |
var props = prop_string.split('.'), | |
p = props.length, | |
result = obj, | |
i = 0, | |
prop; | |
for (; i<p; i++) { | |
prop = props[i]; | |
result = result[prop]; | |
if (result === undefined) return result; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment