简体   繁体   English

多个字段上的数组过滤

[英]Array filtering on multiple fields

I have this code, which filters my data.我有这个代码,它过滤我的数据。 I'm asking me, if there is a way not to filter each field ( id , mandant , zonenlogik ...) explicitly.我问我,是否有办法不明确过滤每个字段( idmandantzonenlogik ...)。 Maybe there is a more smooth way to set the filter on all fields without calling them explicitly?也许有一种更流畅的方法来在所有字段上设置过滤器而不显式调用它们?

let filteredList = this.state.freights.filter((freight) => {

    if (freight.id.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.mandant.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.zonenlogik.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.frachtart_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.transportart_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.spedit_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.spedit2_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
    if (freight.lager_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
        return freight;
    }
});

You can fetch the object values using Object.values() and then loop over those to check whether a substring is present in the string and then return the filtered object您可以使用Object.values()获取对象值,然后遍历这些值以检查字符串中是否存在子字符串,然后返回过滤后的对象

let filteredList = this.state.freights.filter((freight) => {
    let search = this.state.search.toLowerCase();
    var values = Object.values(freight);
    var flag = false
    values.forEach((val) => {
      if(val.toLoweCase().indexOf(search) > -1) {
           flag = true;
           return;
       }
     }
     if(flag) return freight
});

I'm assuming that you want another code that achieves the same result as the code you posted.我假设您想要另一个与您发布的代码实现相同结果的代码。 Here is mine:这是我的:

 const searchTerm = this.state.search.toLowerCase(); let filteredList = this.state.freights.filter((freight) => { // get all keys of freight const keys = Object.keys(freight).map(k => k.toLowerCase()); for (let k of keys) { // if key (eg id) matches the search term, return freight if (k.indexOf(searchTerm) !== 1) { return true; // we want this freight object } } return false; });

Here is the es5 one-liner (sort of):这是 es5 单行(有点):

let filteredList = this.state.freights.filter(freight =>
  Object.keys(freight).some(
    key =>
      freight[key]
        .toLowerCase()
        .indexOf(this.state.search.toLowerCase()) !== -1,
  ),
);

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

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