Created
September 16, 2013 19:02
-
-
Save humphd/6584999 to your computer and use it in GitHub Desktop.
safeLookup of a JSON inflated object along a 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
| function safeLookup(obj, propPath, fallback) { | |
| fallback = fallback || ''; | |
| var props = propPath.split('.'); | |
| // Descend obj along the path specified in propPath, but | |
| // don't trust that that path is good, and may contain | |
| // undefined routes. | |
| try { | |
| props.forEach(function(prop) { | |
| obj = obj[prop]; | |
| }); | |
| return obj || fallback; | |
| } catch (e) { | |
| return fallback; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment