如何用filter与includes实现对象属性的多词逻辑搜索
如何用filter与includes实现对象属性的多词逻辑搜索
嘿,这需求太常见了!完全可以用Array.filter()搭配字符串的includes()来实现,而且不用写繁琐的循环,代码还能适配动态数量的搜索词,刚好满足你要的「包含所有词(AND)」和「包含任意词(OR)」两种逻辑,我给你拆解一下:
先拿你提供的示例数据来演示,先把数据存好:
const products = [ { "produkt": "Produkt 1", "description": "x1, x2, x3, x4" }, { "produkt": "Produkt 1", "description": "x2, x3" }, { "produkt": "Produkt 1", "description": "x1, x4" } ];
假设你的动态搜索词是一个数组,比如要搜['x1', 'x2'],接下来分两种逻辑实现:
1. 「包含任意搜索词」的OR逻辑
只要产品的description里有至少一个搜索词就算匹配,这里可以用Array.some()来配合——some()会遍历搜索词数组,只要有一个词被description包含,就返回true,刚好对应OR逻辑:
const searchTerms = ['x1', 'x2']; // OR 搜索:包含任意一个关键词 const orResults = products.filter(product => { return searchTerms.some(term => product.description.includes(term)); }); // 结果会返回所有三个产品(第一个含x1/x2,第二个含x2,第三个含x1) console.log(orResults);
2. 「包含所有搜索词」的AND逻辑
需要产品的description里同时包含所有搜索词,这时候用Array.every()就对了——every()会要求搜索词数组里的每一个词都能在description中找到,才返回true,完美对应AND逻辑:
// AND 搜索:包含所有关键词 const andResults = products.filter(product => { return searchTerms.every(term => product.description.includes(term)); }); // 结果只会返回第一个产品(只有它同时包含x1和x2) console.log(andResults);
小补充(可选优化)
如果你的description格式可能有变动(比如分隔符不是, ,或者关键词有大小写差异),可以先做个小处理让匹配更严谨:
// 先把description转成小写的关键词数组,避免大小写问题,同时兼容各种分隔符 const getKeywords = (desc) => desc.toLowerCase().split(/,\s*/); // 优化后的OR搜索 const optimizedOrResults = products.filter(product => { const keywords = getKeywords(product.description); return searchTerms.some(term => keywords.includes(term.toLowerCase())); });
这样不管关键词是大写还是小写,或者分隔符有没有空格,都能准确匹配啦~
备注:内容来源于stack exchange,提问作者bluelemonade




