【问题标题】:How to apply filter on different key values of Objects which are in array in React Native如何对 React Native 中数组中对象的不同键值应用过滤器
【发布时间】:2020-10-15 18:37:40
【问题描述】:

我正在尝试将过滤器应用于具有对象的数组,并且我希望获得结果,就好像我在搜索栏中键入国家或名称或值并获得与特定查询相关的结果一样。 请帮助我如何实现。目前,我能够获得一个值的结果,但我希望任何查询都可以给出结果。 这是我的数组:

 data: [
    { id: "1", value: "Zaid Qureshi", country: "Pakistan", price: "23" },
    { id: "2", value: "Wasiq Safdar", country: "UK", price: "23" },
    { id: "3", value: "Bilal Hasan", country: "US", price: "23" },
    { id: "4", value: "Waqas Hasan", country: "Austria", price: "23" },
    { id: "5", value: "Malik Mati", country: "Saudia", price: "23" },
    { id: "6", value: "Zeeshan", country: "Japan", price: "23" },
    { id: "7", value: "ABC", country: "China", price: "23" },
    { id: "8", value: "DEF", country: "Isreal", price: "23" },
    { id: "9", value: "GHI", country: "Canada", price: "23" },
    { id: "10", value: "JKL", country: "Inda", price: "23" },
  ],

目前我正在这样做

 const searchData = this.state.data.filter((item) =>
      item.value.toLowerCase().includes(search.toLowerCase())
    );

【问题讨论】:

    标签: javascript arrays reactjs react-native filter


    【解决方案1】:
    const searchData = this.state.data.filter((item) =>
      item.value.toLowerCase().includes(search.toLowerCase()) ||
      item.country.toLowerCase().includes(search.toLowerCase()) || 
      item.price.toLowerCase().includes(search.toLowerCase())
    );
    

    你可以让它更加动态,这样每次你添加新的键值时,你就不需要再通过放置另一个 OR 来修改逻辑

    let searchData = data.filter((item) =>{
      for(key in item)
      {
       if(item[key].toLowerCase().includes(search.toLowerCase()))
       {
          return true
       }
      }
      return false
    
    }
    );
    

    【讨论】:

      【解决方案2】:

      您只需使用 OR 运算符。

      运算符的快速亮点:&& 逻辑 (AND) - ||逻辑 (OR)。

      
      const searchData = this.state.data.filter((item) =>
        item.value.toLowerCase().includes(search.toLowerCase()) 
      ||
        item.country.toLowerCase().includes(search.toLowerCase()) 
      || 
        item.price.toLowerCase().includes(search.toLowerCase())
      );
      
      

      祝你项目顺利

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 2019-10-28
        • 2022-07-20
        • 2020-01-17
        相关资源
        最近更新 更多