You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于键值对数组过滤含复杂嵌套对象的产品数组?

实现方案

核心思路

利用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:36:31