简体   繁体   English

使用lodash过滤器时如何包含null / undefined值

[英]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. 如果该属性为false或未定义/空,则希望包含它。 In the example below, I am summing by the deliciousRating as long as isBruised is not true. 在下面的示例中,只要isBruised是不正确的,我就按DeliciousRating求和。 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]. 我希望它返回19,但目前它只从apples [1]获得DeliciousRating。

I would use native filter function .filter((v) => !v.isBruised) . 我会使用本机过滤器函数.filter((v) => !v.isBruised) Will include deliciousRating key either if isBruised is null , undefined , false or if doesn't exist. 将包括deliciousRating键后,如果isBruisednullundefinedfalse或者不存在。

 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() . 使用_.reject()而不是_.filter() The _.reject() method is... _.reject()方法是...

The opposite of _.filter; _.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: 在香草JS中,您可以使用Array#reduce来汇总未遭受瘀伤的项目:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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