You need to enable JavaScript to run this app. 如何过滤两个数组获取关联对象,将对应产品归入所属分类?
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤两个数组获取关联对象,将对应产品归入所属分类?

实现方案

你可以通过先构建分类ID映射表的方式高效完成数据组装,避免频繁遍历分类数组,JavaScript实现代码如下:

完整代码

// 初始化分类映射表与带products字段的分类结果数组
const categoryIdMap = {}
const categoriesProducts = categories.map(category => {
  const formattedCategory = { ...category, products: [] }
  categoryIdMap[category.id] = formattedCategory
  return formattedCategory
})

// 遍历产品列表,将产品推入对应分类
productsList.forEach(product => {
  // 提取需要存入的产品字段,可按需扩展
  const productBaseInfo = {
    id: product.id,
    name: product.name
  }
  // 遍历产品所属的所有分类匹配对应项
  product.categories.forEach(belongCategory => {
    const targetCategory = categoryIdMap[belongCategory.id]
    targetCategory && targetCategory.products.push(productBaseInfo)
  })
})

// 【可选操作】如果需要过滤掉无关联产品的分类,执行以下代码
const result = categoriesProducts.filter(item => item.products.length)

运行后得到的result数组就是你要求的输出结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 00:36:14