In some templating frameworks it can be really annoying reading a nested property of a JS object as it can of mean chaining a heap of null checks together....
for instance if I need to access a nested property 'to' in 'email.addresses.to' safely it means having to do something like:
if(email && (adresses = email.addresses)) { //print addresses.to }
This is verbose and annoying. I needed a function that would return the nested value, or simply return an empty string if any property in the chain was null or undefined
i.e.
safeRead(email, 'addresses', 'to');
I also wanted property chains can be as long or short as I'd like.... ie.:
safeRead(my, 'very', 'deeply', 'nested', 'property');
The finished product:
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
// | |
// 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; | |
}; |