如何用对象数组过滤另一个对象数组?(产品搜索场景)
用对象数组实现多维度产品搜索过滤
我来帮你搞定这个多维度产品过滤的需求!核心思路就是用过滤条件数组里的每一条规则,去逐一校验产品数组里的每个产品,只有满足所有规则的产品才会被保留下来。下面直接上代码和详细解释:
基础单值过滤实现
首先补全你提供的产品数组(假设Product4的category字段是完整的),然后定义过滤条件数组,再实现核心过滤逻辑:
// 完整的主产品数组 const products = [ { id: 1, name: 'Product 1', category: 'Home', skill: 'Easy', color: 'blue', price: 100.00 }, { id: 2, name: 'Product 2', category: 'Home', skill: 'Intermediate', color: 'red', price: 120.00 }, { id: 3, name: 'Product 3', category: 'Office', skill: 'Intermediate', color: 'green', price: 190.00 }, { id: 4, name: 'Product 4', category: 'Office', skill: 'Advanced', color: 'blue', price: 250.00 } ]; // 过滤条件数组:筛选「类别为Home」且「技能难度为Intermediate」的产品 const filters = [ { key: 'category', value: 'Home' }, { key: 'skill', value: 'Intermediate' } ]; // 执行过滤 const filteredProducts = products.filter(product => { // 确保当前产品满足所有过滤条件 return filters.every(filter => { return product[filter.key] === filter.value; }); }); console.log(filteredProducts); // 输出结果:[{ id: 2, name: 'Product 2', category: 'Home', skill: 'Intermediate', color: 'red', price: 120.00 }]
扩展:支持多值过滤(比如多选颜色)
如果需要支持某个维度多选(比如同时选蓝色和红色),可以稍微调整逻辑,让过滤值支持数组类型:
// 支持多值的过滤条件:筛选「Home类别」且「颜色为blue或red」的产品 const multiValueFilters = [ { key: 'category', value: 'Home' }, { key: 'color', value: ['blue', 'red'] } ]; const filteredProductsMulti = products.filter(product => { return multiValueFilters.every(filter => { if (Array.isArray(filter.value)) { // 多值匹配:检查产品属性是否在可选值数组中 return filter.value.includes(product[filter.key]); } else { // 单值匹配 return product[filter.key] === filter.value; } }); }); console.log(filteredProductsMulti); // 输出结果:[Product1, Product2]
额外优化建议
- 大小写兼容:如果用户输入的筛选值和产品属性大小写不一致(比如用户输入
home而产品是Home),可以统一转成小写比较:return product[filter.key].toLowerCase() === filter.value.toLowerCase(); - 范围过滤(比如价格):如果需要价格区间筛选,可以给过滤条件加操作符字段:
const priceFilters = [{ key: 'price', operator: '>=', value: 150 }]; // 过滤逻辑里判断操作符 return priceFilters.every(filter => { switch(filter.operator) { case '>': return product[filter.key] > filter.value; case '>=': return product[filter.key] >= filter.value; case '<': return product[filter.key] < filter.value; case '<=': return product[filter.key] <= filter.value; default: return product[filter.key] === filter.value; } }); - 空过滤处理:如果过滤条件数组为空,直接返回全部产品,避免出现无结果的情况:
const filteredProducts = filters.length === 0 ? [...products] : products.filter(/* ... */);
内容的提问来源于stack exchange,提问作者Nabarag Paul
相关产品推荐
相关产品推荐

