Created
August 6, 2014 19:06
-
-
Save AaronHolbrook/e1a045f70ef933fc80b3 to your computer and use it in GitHub Desktop.
Safely read any number of properties from a JSON object
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
/** | |
* Safe read to check any amount of properties are safe to traverse | |
* From: http://thecodeabode.blogspot.com.au/2013/04/javascript-safely-reading-nested.html | |
* | |
* Usage... for a nested structure | |
* var test = { | |
* nested: { | |
* value: 'Read Correctly' | |
* } | |
* }; | |
* safeRead(test, 'nested', 'value'); // returns 'Read Correctly' | |
* safeRead(test, 'missing', 'value'); // returns '' | |
* | |
* http://thecodeabode.blogspot.com.au/2013/04/javascript-safely-reading-nested.html | |
* | |
* @returns {*} | |
*/ | |
var safeRead = function () { | |
var current, obj, prop, props, val, _i, _len, read; | |
obj = arguments[0]; | |
props = (2 <= arguments.length) ? [].slice.call( arguments, 1 ) : []; | |
read = function ( obj, prop ) { | |
if ( ( obj !== null ? obj[ prop ] : void 0 ) === null ) { | |
return; | |
} | |
return obj[prop]; | |
}; | |
current = obj; | |
for ( _i = 0, _len = props.length; _i < _len; _i ++ ) { | |
prop = props[ _i ]; | |
val = read( current, prop ); | |
if ( val ) { | |
current = val; | |
} | |
else { | |
return ''; | |
} | |
} | |
return current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment