如何简化数组过滤器

How to simplify array filter

我想知道如何简化它以避免重复小写并包含每个 属性 的条件。

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

谢谢!

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

  1. 使用 map 将值转换为小写(您可以使用 for...in 循环来 转换所有属性)
  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...
});

如果你真的想降低重复次数,你可以这样做。

 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]) 像您所有的 || 语句一样工作。如果关键字在任何字段中,它将 return 为真。