简体   繁体   中英

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:

  1. Use map to convert values to lowercase (you can use for...in loop to transform all properties)
  2. Apply filter on the result of the 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. then you list the fields you want to include in the or filter you're using.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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