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

JavaScript中如何合并对象数组内相同brandId的item属性?

实现JavaScript数组按brandId聚合的方法

直接通过JS内置的数组方法即可实现,以下是具体实现方案:

实现思路

  • 用Map结构作为临时映射容器,以brandId作为唯一键存储聚合后的品牌数据,避免重复判断
  • 遍历原始数组,将同brandId的item合并到同一个数组中
  • 最后将Map结构转为普通数组即可,可根据需求调整单条item的输出格式

代码实现

方案1:item统一为数组(更推荐,后续处理无需判断类型)

const result = Array.from(
  data.reduce((map, { brandId, brand, item }) => {
    if (!map.has(brandId)) {
      map.set(brandId, { brandId, brand, item: [] })
    }
    map.get(brandId).item.push(item)
    return map
  }, new Map()).values()
)

方案2:严格匹配你给出的预期格式(单个item保留对象类型)

const tempMap = data.reduce((map, { brandId, brand, item }) => {
  if (!map.has(brandId)) {
    map.set(brandId, { brandId, brand, item: [] })
  }
  map.get(brandId).item.push(item)
  return map
}, new Map())

const result = Array.from(tempMap.values()).map(brand => {
  return brand.item.length === 1 
    ? { ...brand, item: brand.item[0] } 
    : brand
})

说明

  • 整体时间复杂度为O(n),仅需要遍历一次原始数组,性能表现较好
  • 更建议统一将item设置为数组格式,后续业务逻辑处理时无需额外判断字段类型,可降低出错概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:42:01