当尝试使用未定义属性进行筛选时,Lodash将排除项

Lodash excludes items when trying to filter with an undefined property

本文关键字:筛选 Lodash 排除 属性 未定义      更新时间:2023-09-26

我使用lodash _.where来过滤数组。当filters的属性未定义时,lodash尝试匹配未定义的值,而不是完全忽略该属性。

var list = [{
    type: 'something',
    units: [{bar: 1}]
}];
var filters = {};

var filteredlist = _(list)
.where(filters.type ? { 
  type: filters.type
} : {})
.where(filters.view === 'foo' && filters.bar ? { 
  units: [{
    bar: +filters.bar
  }]
} : {})
.value();
filteredlist;

上面返回list中的唯一项。

但是我必须检查filters中的属性是否存在,然后使用_.where_.filter来过滤我的list

如果我只是做了:

var filteredlist = _(list)
.where({ 
  type: filters.type,
  units: [{
    bar: +filters.bar
  }]
})
.value();

我没有得到任何回报,因为filters.typefilters.bar没有定义…

是否有一个本地的方式,我可以有lodash让项目通过_.where_.filter(或替代),如果我试图过滤的属性是未定义的或假的?最好没有mixin,但如果你有一个优雅的解决方案,请随时分享。

我认为这可能是你正在寻找的大致范围:

_(list).filter(function (item) {
  return _.has(filters, 'type') ? _.isEqual(filters.type, item.type) : true;
}).value()

但是,如果您需要检查过滤器中的所有键,那么您可能需要这样做:

_(list).filter(function (item) {
  var pass = true;
  _.each(filters, function (v, k) {
      if (!_.isEqual(item[k], v)) { 
          pass = false;
      }
  });
  return pass;
}).value()