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

如何过滤嵌套对象数组以获取包含指定产品类型的公司及对应符合条件的产品?

解决方法:过滤包含指定产品类型的公司并保留对应产品

我来帮你搞定这个问题!先看看你当前代码的问题:你的filter回调函数里没有返回值(用了大括号却没写return),所以过滤后的数组其实是空的。而且就算修正了返回值,也只是筛选出了符合条件的公司,没处理products数组——还是会保留所有产品,达不到你要的只留Timespot产品的效果。

我们需要分两步实现需求:

  • 第一步:筛选出至少有一个Timespot产品的公司
  • 第二步:对每个筛选出来的公司,只保留它的Timespot产品

完整实现代码

const dummyData = [
  { companyName: "Company A", products: [{ productType: "Variabel pris" }] },
  { companyName: "Company B", products: [{ productType: "Fastpris" }, { productType: "Fastpris" }, { productType: "Fastpris" }, { productType: "Timespot" }] },
  { companyName: "Company C", products: [{ productType: "Spotpris" }, { productType: "Timespot" }] }
];

const result = dummyData
  // 第一步:过滤出包含Timespot产品的公司
  .filter(company => company.products.some(product => product.productType === "Timespot"))
  // 第二步:对每个符合条件的公司,只保留Timespot产品
  .map(company => ({
    ...company, // 复制原公司的其他字段(这里仅companyName)
    products: company.products.filter(product => product.productType === "Timespot")
  }));

console.log(result);

代码细节解释

  1. filter阶段:用some方法检查当前公司的产品数组里是否存在productType为"Timespot"的产品,返回true的公司会被保留。这里箭头函数直接返回表达式结果,不用大括号(如果用大括号一定要加return)。
  2. map阶段:为每个筛选后的公司创建新对象:
    • 用扩展运算符...company复制原公司的所有属性(这里就是companyName)
    • 重新赋值products字段,用filter方法只保留符合条件的产品

验证结果

运行代码后,得到的结果和你预期完全一致:

[
  { companyName: "Company B", products: [{ productType: "Timespot" }] },
  { companyName: "Company C", products: [{ productType: "Timespot" }] }
]

如果你想一步完成逻辑,也可以用reduce方法(可读性稍弱,但适合追求代码紧凑的场景):

const result = dummyData.reduce((acc, company) => {
  const timespotProducts = company.products.filter(p => p.productType === "Timespot");
  if (timespotProducts.length > 0) {
    acc.push({ ...company, products: timespotProducts });
  }
  return acc;
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:27:42