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
相关产品推荐
相关产品推荐

