简体   繁体   English

如何简化数组过滤器

[英]How to simplify array filter

I want to know how to simplify this in order to avoid duplicating the lower case and includes condition for each property.我想知道如何简化它以避免重复小写并包含每个属性的条件。

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

Thanks!谢谢!

You can use the map function before applying the filter:在应用过滤器之前,您可以使用 map function:

  1. Use map to convert values to lowercase (you can use for...in loop to transform all properties)使用 map 将值转换为小写(您可以使用 for...in 循环来转换所有属性)
  2. Apply filter on the result of the map.对 map 的结果应用过滤器。
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...
});

if you really want to lower the repetition you could do something like this.如果你真的想降低重复次数,你可以做这样的事情。

 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
 }

you make the .toLowerCase().includes(this.table.filter.keyword) into it's own function.你把.toLowerCase().includes(this.table.filter.keyword)变成它自己的 function。 then you list the fields you want to include in the or filter you're using.然后列出要包含在or正在使用的过滤器中的字段。

You then take fields.some(f => lowerIncludes(item[f]) to work like all of your || statements. If the keyword is in any of the fields, it will return true.然后,您将fields.some(f => lowerIncludes(item[f])像所有||语句一样工作。如果关键字在任何字段中,它将返回 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM