如何在对象数组的嵌套数组中通过单个字符实现模糊匹配检索
嵌套数组模糊字符检索实现方案
原代码问题说明
res.tags()写法错误:tags是对象的数组属性不是方法,不需要加括号调用,直接写res.tags即可- 直接使用
Array.includes()对tags数组做匹配是全量元素匹配,只能匹配完全等于检索值的tag,无法实现部分字符模糊检索
正确实现代码
基础版本(区分大小写)
const arr = [{ x: 1, tags: ["tag1", "taf", "ee", "xx"] },{ x: 3, tags: ["ta", "e", "xx"] }]; // 例如检索字符为 "ta" const searchKey = "ta"; const fResult = arr.filter(item => { // 只要tags数组中有任意一个tag包含检索字符,就保留当前对象 return item.tags.some(tag => tag.includes(searchKey)); });
优化版本(大小写不敏感,适配更多检索场景)
const arr = [{ x: 1, tags: ["tag1", "taf", "ee", "xx"] },{ x: 3, tags: ["ta", "e", "xx"] }]; function filterByTag(arr, searchKey) { const matchKey = searchKey.toLowerCase(); return arr.filter(item => item.tags.some(tag => tag.toLowerCase().includes(matchKey)) ); } // 测试用例 console.log(filterByTag(arr, "t")); // 返回两个元素,所有带t的tag对应的对象 console.log(filterByTag(arr, "TA")); // 大小写不敏感,同样返回两个元素 console.log(filterByTag(arr, "tag")); // 仅返回x=1的元素
核心逻辑说明
- 使用
Array.some()遍历tags数组,只要存在1个符合匹配规则的tag就返回true,保留当前外层数组元素 - 使用
String.includes()判断单个tag字符串是否包含输入的检索子串,实现单字符/部分字符的匹配需求 - 转小写的处理可根据实际需求选择是否保留,不需要严格区分大小写的场景建议保留,提升检索友好度
内容的提问来源于stack exchange,提问作者ahmed mersal
相关产品推荐
相关产品推荐

