首页 > 解决方案 > 如何过滤 JSON 数组,在 keyup 处使用 eventListener 输入值

问题描述

我想构建一个搜索过滤器,例如 forEach 通过一组 obj 像这样:

const lngLatLocation = [
  {
    "id": "alster",
    "name": "Alster",
    "link": "https://en.wikipedia.org/wiki/Alster",
    "coordinates": [9.997649, 53.557344]
  },
  {
    "id": "elbphilharmonie",
    "name": "Elbphilharmonie",
    "link": "https://www.elbphilharmonie.de/en/elbphilharmonie",
    "coordinates": [9.984198, 53.541267]
  },
  {
    "id": "rathaus",
    "name": "Rathaus / TownHall",
    "link": "https://en.wikipedia.org/wiki/Hamburg_City_Hall",
    "coordinates": [9.992061, 53.550252]
  },
  {
    "id": "aplantenUnBloomen",
    "name": "Planten Un Blomen",
    "link": "https://www.hamburg.com/explore/outdoors/11872624/planten-un-blomen/",
    "coordinates": [9.982028, 53.560427]
  }
]

并使用名称的输入字段进行过滤。每个键位一个。

      document.querySelector('.location-filter').addEventListener('keyup', () => {
        // FILTER HERE FOR INPUT VALUE
        const filteredLocations = lngLatLocation.filter(({name}) => name == input.value);
        console.log(filteredLocations);

      });

在我的示例中,当我区分大小写并且字符串完整时,我只是在查找“Alster”。

我想要的是,当我在输入中键入“a”时,他应该从 json-array 中搜索第一个字母为“a”的所有项目并将它们放入新数组中。就像一个反应式搜索过滤器。

标签: javascriptarraysjsonfilter

解决方案


虽然我没有通过执行它来验证我的解决方案,但我觉得你需要稍微调整一下你的过滤器。

如果您想要不区分大小写,我会尝试

lngLatLocation.filter(({name}) => name.toLowerCase().startsWith(prefix.toLowerCase()));

并且您更喜欢区分大小写,然后只需删除.toLowerCase()


推荐阅读