I\'ve got a collection of disparate, complex JSON objects from a CouchDB database. Each contains many levels of nested properties--for example,
tps_report.p
/**
* units sold from each TPS report
*/
var units;
// the hard way
units = (report && report.personnel && report.personnel.info &&
report.personnel.info.sales && report.personnel.info.sales.units &&
report.personnel.info.sales.units.sold) || 0;
// the easy way
units = selectn('personnel.info.sales.units.sold', report) || 0;
// resulting action
if (units < 10) fireEmployee();
Shameless plug: I am the author of selectn. It is avaialble via npm install selectn
or bower install selectn
or component install wilmoore/selectn
.
Check out the examples on the readme to find out why this is better than an isset
clone. You can also use it as a filter predicate so you can scrub out nested objects that do not contain a particular deeply nested property.