Skip to content

Instantly share code, notes, and snippets.

@benkitzelman
Last active December 16, 2015 03:49
Show Gist options
  • Save benkitzelman/5372419 to your computer and use it in GitHub Desktop.
Save benkitzelman/5372419 to your computer and use it in GitHub Desktop.
A safe format function to read deeply nested properties (i.e. my.nested.value)... If any property in the chain is null or undefined, an empty string will be returned
//
// 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