javascript - 如何过滤 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”的所有项目并将它们放入新数组中。就像一个反应式搜索过滤器。
解决方案
虽然我没有通过执行它来验证我的解决方案,但我觉得你需要稍微调整一下你的过滤器。
如果您想要不区分大小写,我会尝试
lngLatLocation.filter(({name}) => name.toLowerCase().startsWith(prefix.toLowerCase()));
并且您更喜欢区分大小写,然后只需删除.toLowerCase()
推荐阅读
- path - 在指定路径名时,我必须在哪些操作系统中使用“单点后跟斜杠”?
- php - 应用于大型数组时,PHP Foreach 循环太慢
- python - 如何在 Python 中将 000-000 更改为 000000?
- python - python/numpy一次组合4行子数组
- html - Nunjucks 嵌套变量
- bitbucket - 配置 bitbucket 插件以避免对安全变量进行硬编码
- r - 嵌套狄利克雷过程的演示代码
- mysql - 在“Where”子句中组合两个子查询的好选择
- clojure - Leiningen:无法使用“不安全”的代理存储库
- javascript - selenium javascript textarea值错误