如何简化数组过滤器

问题描述 投票:-1回答:2

我想知道如何简化此过程,以避免重复小写字母,并包括每个属性的条件。

 items() {
  return this.table.filter.keyword
    ? this.dataArray.filter(
        item =>
          item.nombre.toLowerCase().includes(this.table.filter.keyword) ||
          item.paisOrigen
            .toLowerCase()
            .includes(this.table.filter.keyword) ||
          item.ciudad.toLowerCase().includes(this.table.filter.keyword) ||
          item.sector.toLowerCase().includes(this.table.filter.keyword) ||
          item.contratadorPor
            .toLowerCase()
            .includes(this.table.filter.keyword) ||
          item.moneda.toLowerCase().includes(this.table.filter.keyword)
      )
    : this.dataArray;
}

谢谢!

javascript arrays function vue.js arrow-functions
2个回答
1
投票

您可以在应用过滤器之前使用地图功能:

  1. 使用映射将值转换为小写(您可以在循环中使用...转换所有属性)
  2. 在地图结果上应用过滤器。
this.data.map(item => {
  let ret = {};
  for (let p in item) {
    ret[p] = item[p].toLowerCase();
  }
  return ret;
}).filter(item => {
  //... perform your filter logic here...
});

0
投票

如果您真的想降低重复次数,可以执行以下操作。

 items() {
  const lowerIncludes(val) => val.toLowerCase().includes(this.table.filter.keyword)
  const fields = ['nombre', 'paisOrigen', 'ciudad', 'sector', 'contratadorPor', 'moneda']
  return this.table.filter.keyword ? this.dataArray.filter(item => fields.some(f => lowerIncludes(item[f]))) : this.dataArray
 }

您将.toLowerCase().includes(this.table.filter.keyword)设置为自己的功能。然后列出要包含在您正在使用的or过滤器中的字段。

然后您将fields.some(f => lowerIncludes(item[f])用作所有||语句。如果关键字在任何字段中,它将返回true。

© www.soinside.com 2019 - 2024. All rights reserved.