多个字段的数组过滤

IT技术 javascript arrays reactjs filter
2021-05-11 09:14:18

我有这个代码,它过滤我的数据。我在问我,是否有一种方法可以不显式过滤每个字段 ( id, mandant, zonenlogik...)。也许有更流畅的方法来在所有字段上设置过滤器而不显式调用它们?

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;
    }
});
3个回答

您可以使用获取对象值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
});

我假设您想要另一个与您发布的代码实现相同结果的代码。这是我的:

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 (e.g id) matches the search term, return freight
      if (k.indexOf(searchTerm) !== 1) {
        return true; // we want this freight object
      } 
    }
    return false;
});

这是 es5 one-liner(有点):

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