如何对含字符串数组属性的对象数组实现部分字符串匹配过滤?
字符串数组部分匹配筛选实现方案
错误原因
Array.prototype.includes() 执行的是完全相等匹配,你之前的写法是判断 tags 数组中是否存在值完全等于搜索字符的元素,而非判断某个元素的内容包含搜索字符,因此无法得到预期结果。
核心实现
搭配 Array.prototype.some() 遍历 tags 数组的每一个字符串元素,再用 String.prototype.includes() 对单个字符串做部分匹配,只要任意一个 tag 包含搜索关键词就保留当前对象:
const searchKeyword = "n"; const filtered = array.filter(entry => entry.tags.some(tag => tag.includes(searchKeyword)) );
可选扩展
- 如需实现大小写不敏感匹配,可以在匹配前统一转为小写/大写:
const searchKeyword = "N".toLowerCase(); const filtered = array.filter(entry => entry.tags.some(tag => tag.toLowerCase().includes(searchKeyword)) );
- 如需筛选所有 tag 都包含搜索关键词的对象,将
some()替换为every()即可。
内容的提问来源于stack exchange,提问作者Josh Susa
相关产品推荐
相关产品推荐

