如何基于键值对数组过滤含复杂嵌套对象的产品数组?
实现方案
核心思路
利用Array.filter()遍历产品数组,结合Array.every()验证每个产品的attributes是否完全匹配所有过滤条件——只有当所有过滤键值对都匹配时,该产品才会被保留。
情况1:过滤条件为对象形式(最常用)
如果你的filters是键值对对象(比如{ color: 'blue', size: 'L' }),可以这样实现:
// 示例产品数组 const products = [ { id: 1, name: '纯棉T恤', attributes: { color: 'blue', size: 'L', material: 'cotton' } }, { id: 2, name: '牛仔长裤', attributes: { color: 'black', size: 'M', material: 'denim' } }, { id: 3, name: '聚酯纤维卫衣', attributes: { color: 'blue', size: 'L', material: 'polyester' } } ]; // 过滤条件对象 const filters = { color: 'blue', size: 'L' }; // 提前将过滤条件转为键值对数组,避免循环内重复计算 const filterEntries = Object.entries(filters); // 执行筛选 const filteredProducts = products.filter(product => { const attrs = product.attributes; // 验证所有过滤条件是否匹配 return filterEntries.every(([key, value]) => attrs[key] === value); }); console.log(filteredProducts); // 输出:id为1和3的产品
情况2:过滤条件为键值对数组形式
如果你的filters是数组结构(比如[{ key: 'color', value: 'blue' }, { key: 'size', value: 'L' }]),直接遍历数组验证即可:
const filters = [ { key: 'color', value: 'blue' }, { key: 'size', value: 'L' } ]; const filteredProducts = products.filter(product => { const attrs = product.attributes; return filters.every(({ key, value }) => attrs[key] === value); });
效率说明
- 时间复杂度为
O(n*m):n是产品数量,m是过滤条件的数量,这是此类需求的最优复杂度(必须检查每个产品的所有条件)。 - 提前将过滤条件转为键值对数组(对象形式的情况),避免在
filter循环内重复调用Object.entries(),减少不必要的性能开销。
边界处理
如果产品的attributes中缺少某个过滤条件的键,会返回undefined,与过滤值不匹配,该产品会被自动过滤,符合“完全匹配所有键值对”的需求。
内容的提问来源于stack exchange,提问作者ghost
相关产品推荐
相关产品推荐

