如何不使用for循环过滤JSON数组,实现指定关键词匹配?
问题描述
给定如下JSON对象数组:
[ { "id": 1, "full_name": "John Doe" }, { "id": 2, "full_name": "John T Doe" }, { "id": 3, "full_name": "John T. Doe" }, { "id": 4, "full_name": "Jon Dough" } ]
能否不使用for循环对该列表进行过滤,当搜索查询为"John Doe"时,返回包含记录1-3的过滤数组(不包含记录4)?规则为:只要对象的full_name中出现"John"或"Doe"即视为匹配。
解决方案
完全可以,直接用数组原生的filter方法就能实现,不需要手动编写for循环。具体实现思路和代码如下:
实现步骤
- 将搜索查询拆分为独立关键词数组,比如把"John Doe"拆成
["John", "Doe"] - 调用数组的
filter方法,结合some方法判断每个对象的full_name是否包含任意一个关键词
代码示例
const data = [ { "id": 1, "full_name": "John Doe" }, { "id": 2, "full_name": "John T Doe" }, { "id": 3, "full_name": "John T. Doe" }, { "id": 4, "full_name": "Jon Dough" } ]; const searchQuery = "John Doe"; const keywords = searchQuery.split(' '); const filteredData = data.filter(item => { return keywords.some(keyword => item.full_name.includes(keyword)); }); console.log(filteredData); // 输出结果为id 1、2、3的三个对象
扩展说明
filter方法内部会完成遍历逻辑,但不需要开发者手动写for循环,完全符合需求some方法会在数组中有任意一个元素满足条件时返回true,刚好对应"出现John或Doe即匹配"的规则- 如果需要支持大小写不敏感的匹配,可以统一转换为小写(或大写)后再判断:
const filteredData = data.filter(item => { const lowerName = item.full_name.toLowerCase(); return keywords.some(keyword => lowerName.includes(keyword.toLowerCase())); });
内容的提问来源于stack exchange,提问作者js-newb
相关产品推荐
相关产品推荐

