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

时间:2017-11-06 22:35:42

标签: javascript filter lodash

我想过滤特定的对象属性。如果该属性为false或undefined / null,我希望它包含在内。在下面的例子中,只要isBruised不是真的,我就会通过deliciousRating求和。但是,我无法弄清楚如何包含undefined / null值。

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

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

我希望这会返回19,但目前它只是从苹果[1]获得deliciousRating。

2 个答案:

答案 0 :(得分:1)

我会使用原生过滤功能.filter((v) => !v.isBruised)。如果deliciousRatingisBruisednullundefined或者如果不存在,则会包含false密钥。



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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用_.reject()代替_.filter()_.reject()方法是......

  

与_.filter相反;此方法返回元素   谓词不能回归的集合。

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

var result = _.sumBy(_.reject(apples, 'isBruised'), 'deliciousRating');

console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

在vanilla JS中,您可以使用Array#reduce来计算未受伤的项目:

&#13;
&#13;
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);
&#13;
&#13;
&#13;