在字符串数组中查找项目以过滤平面列表

Find item in array of strings to filter a flatlist

我有一个 FlatList,我正在尝试使用来自下拉选择器的多个输入进行过滤。这是我的 FlatList 组件

      <FlatList
        style={styles.list}
        data={data.filter(filteredUsers)}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
        ListEmptyComponent={EmptyItem}
      />

数据对象中的示例项目

  { id: "2", name: "Harry", city: "Scottdale", state: "AZ", instrument: ["Cowbell", "Ocarina"] },

和使用单个字符串的 filterUsers 函数,它显示数据对象中的所有项目,并在用户开始从下拉列表中选择选项时进行过滤。清除后会再次显示完整数据列表。

  const filteredUsers = (item: { state: string; instrument: string }) => {
    return (
      item.state.toLowerCase().indexOf(state.toLowerCase()) >= 0 &&
      item.instrument.toLowerCase().indexOf(instrument.toLowerCase()) >= 0
    )
  }

我希望在将 instrument 更改为字符串数组而不是单个字符串后拥有相同的功能。

我已将 filteredUsers 中的仪器类型更新为 instrument: Array<string>,但无法弄清楚如何让过滤像更新到阵列之前那样工作。我感谢任何帮助,如果我遗漏了什么,我很乐意提供更多信息。谢谢

这可能是实现所需的一种实现方式objective:

示例数据:

const data = [
  { id: "2", name: "Harry", city: "Scottdale", state: "AZ", instrument: ["Cowbell", "Ocarina"] },
  { id: "2", name: "Harry", city: "Scottsdale", state: "AZ", instrument: ["Towbell", "Ocarina"] },
  { id: "2", name: "Harry", city: "Scottdale", state: "PA", instrument: ["Towbell", "Odarina"] },
];

模拟将用于过滤数据的值:

const state = 'AZ';
const instrument = 'Cowbell';

filteredUsers方法:

const filteredUsers = (item: any) => {
  return (
    item.state.toLowerCase().indexOf(state.toLowerCase()) >= 0 &&
    item.instrument.join().toLowerCase().indexOf(instrument.toLowerCase()) >= 0
  )
}

手动调用过滤器:

console.log(data.filter(filteredUsers));

Link to TypeScript Playground

说明

  • 传入filteredUsers方法的参数设置为any(为简洁起见)。声明对象的道具而不是 any.
  • 可能更合适
  • 将用于过滤的值是 stateinstrument,它们也分别声明(这可能来自 stateprops
  • 搜索 state 时应用现有逻辑
  • 搜索instrument时,item中的newly-transformedArray变成了string(通过使用.join)并将现有逻辑应用于这个新的 string(它是 instrument 数组的所有元素的串联)。

注意:这 most-certainly 不是最佳解决方案。而且,我确定有几点需要更新。很高兴了解更多信息并进行更新。