In javascript, test for property deeply nested in object graph?

后端 未结 6 929
余生分开走
余生分开走 2020-12-03 23:39

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         


        
6条回答
  •  执笔经年
    2020-12-03 23:58

    /**
     * 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.

提交回复
热议问题