Created
August 14, 2014 19:41
-
-
Save gabrysiak/9104092e228ed5c6a3ac to your computer and use it in GitHub Desktop.
Javascript - Read Nested Object Property
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
// | |
// Usage... for a nested structure | |
// var test = { | |
// nested: { | |
// value: 'Read Correctly' | |
// } | |
// }; | |
// safeRead(test, 'nested', 'value'); // returns 'Read Correctly' | |
// safeRead(test, 'missing', 'value'); // returns '' | |
// | |
var safeRead = function() { | |
var current, formatProperty, obj, prop, props, val, _i, _len; | |
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]; | |
if (val = read(current, prop)) { | |
current = val; | |
} else { | |
return ''; | |
} | |
} | |
return current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment