简体   繁体   中英

How to include null/undefined values when using lodash filter

I would like to filter on a particular object property. If that property is false OR undefined/null, I want it included. In the example below, I am summing by the deliciousRating as long as isBruised is not true. However, I can't figure out how to include the undefined/null value.

var apples = [
    {isBruised: true, deliciousRating: 1},
    {isBruised: false, deliciousRating: 10},
    {deliciousRating: 9}
];

_.sumBy(_.filter(apples, ['isBruised', false]), 'deliciousRating');

I would like this to return 19, but currently it is only getting the deliciousRating from apples[1].

I would use native filter function .filter((v) => !v.isBruised) . Will include deliciousRating key either if isBruised is null , undefined , false or if doesn't exist.

 const apples = [ {isBruised: true, deliciousRating: 1}, {isBruised: false, deliciousRating: 10}, {deliciousRating: 9} ]; const r = _.sumBy(apples.filter((v) => !v.isBruised), 'deliciousRating'); console.log(r); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

Use _.reject() instead of _.filter() . The _.reject() method is...

The opposite of _.filter; this method returns the elements of collection that predicate does not return truthy for.

 var apples = [ {isBruised: true, deliciousRating: 1}, {isBruised: false, deliciousRating: 10}, {deliciousRating: 9} ]; var result = _.sumBy(_.reject(apples, 'isBruised'), 'deliciousRating'); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

And in vanilla JS, you can use Array#reduce to sum just the items that are not bruised:

 var apples = [ {isBruised: true, deliciousRating: 1}, {isBruised: false, deliciousRating: 10}, {deliciousRating: 9} ]; var result = apples.reduce(function(s, o) { return o.isBruised ? s : s + o.deliciousRating; }, 0); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM