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

如何在JavaScript中基于对象多条件过滤数组?

解决方案

修正原代码的语法问题

首先你提供的代码存在两处语法错误,需要先修正:

  • Conditionobject中每个属性末尾缺少逗号
  • AllProducts里的Productname值应为字符串类型,需要用引号包裹

修正后的代码如下:

const Conditionobject = {
  Brand: ["msi", "acer"],
  Processor: ["intel i7", "intel i9"],
  Refreshrate: ["165 hz"]
};

const AllProducts = [ 
  {
    Productname: "Acer Nitro",
    Specifications: { Brand: "acer", Processor: "intel i7", Refreshrate: "144 hz"}
  },
  {
    Productname: "Msi Katana",
    Specifications: { Brand: "msi", Processor: "intel i7", Refreshrate: "165 hz"}
  },
  {
    Productname: "Acer Aspire",
    Specifications: { Brand: "acer", Processor: "intel i9", Refreshrate: "165 hz"}
  },
];

实现筛选逻辑

可以通过Array.filter()结合Object.entries()实现多条件筛选,核心逻辑是每个产品必须满足条件对象中所有属性的取值要求。

完整实现代码:

const filteredProducts = AllProducts.filter(product => {
  // 将条件对象转为[key, 允许值数组]的键值对数组
  const conditionEntries = Object.entries(Conditionobject);
  // 检查当前产品是否满足所有条件
  return conditionEntries.every(([key, allowedValues]) => {
    return allowedValues.includes(product.Specifications[key]);
  });
});

console.log(filteredProducts);

逻辑说明

  1. Object.entries(Conditionobject):把条件对象拆分为[["Brand", ["msi", "acer"]], ["Processor", ["intel i7", "intel i9"]], ...]格式的数组,方便遍历每个条件项
  2. conditionEntries.every(...):确保当前产品的Specifications中,每个属性的取值都存在于对应条件的允许值数组里
  3. allowedValues.includes(...):判断产品的属性值是否符合条件要求

输出结果

运行上述代码后,filteredProducts将包含你期望的两个产品:

[
  {
    Productname: "Msi Katana",
    Specifications: { Brand: "msi", Processor: "intel i7", Refreshrate: "165 hz" }
  },
  {
    Productname: "Acer Aspire",
    Specifications: { Brand: "acer", Processor: "intel i9", Refreshrate: "165 hz" }
  }
]

内容的提问来源于stack exchange,提问作者Kyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:25:22