【问题标题】:Lodash excludes items when trying to filter with an undefined propertyLodash 在尝试使用未定义的属性进行过滤时排除项目
【发布时间】:2015-11-05 16:38:08
【问题描述】:

我正在使用 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中的唯一项。

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

如果我只是这样做:

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

我什么也得不到,因为 filters.typefilters.bar 没有定义...

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

【问题讨论】:

  • 您是否需要检查每个列表对象中的每个键是否都存在于过滤器中,或者只是几个特定的​​?

标签: javascript lodash


【解决方案1】:

我认为这可能是您正在寻找的内容:

_(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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多