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

JavaScript中按item_id汇总对象数组quantity值的实现方法

按item_id分组汇总quantity的实现方案

没问题,这是个很典型的分组汇总需求,我给你几个JavaScript的实现方案,从原生高效到简洁的第三方库都有:

方案一:使用Array.reduce()(原生JS基础实现)

这是最直观的原生实现方式,适合数据量不大的场景:

const items = [ 
  {item_id:1,quantity:5}, 
  {item_id:1,quantity:10}, 
  {item_id:2,quantity:45}, 
  {item_id:2,quantity:30}, 
  {item_id:2,quantity:20}, 
  {item_id:3,quantity:10}, 
];

const groupedItems = items.reduce((accumulator, currentItem) => {
  // 在累加器数组中查找当前item_id对应的条目
  const existingItem = accumulator.find(item => item.item_id === currentItem.item_id);
  
  if (existingItem) {
    // 找到则累加quantity
    existingItem.quantity += currentItem.quantity;
  } else {
    // 没找到则新增一个条目(浅拷贝避免修改原对象)
    accumulator.push({...currentItem});
  }
  
  return accumulator;
}, []);

console.log(groupedItems);
// 输出:[ {item_id:1,quantity:15}, {item_id:2,quantity:95}, {item_id:3,quantity:10} ]

方案二:对象映射转数组(性能更优)

如果你的数据量比较大,上面的find方法每次遍历数组会影响性能,推荐用对象做映射(键查找是O(1)复杂度):

const items = [ 
  {item_id:1,quantity:5}, 
  {item_id:1,quantity:10}, 
  {item_id:2,quantity:45}, 
  {item_id:2,quantity:30}, 
  {item_id:2,quantity:20}, 
  {item_id:3,quantity:10}, 
];

// 先创建以item_id为键的映射对象
const itemMap = {};
items.forEach(item => {
  if (itemMap[item.item_id]) {
    itemMap[item.item_id].quantity += item.quantity;
  } else {
    // 初始化新条目
    itemMap[item.item_id] = {...item};
  }
});

// 将映射对象的值转为目标数组
const groupedItems = Object.values(itemMap);

console.log(groupedItems);
// 输出结果和方案一一致

方案三:使用Lodash库(代码更简洁)

如果你的项目已经引入了Lodash,可以用它的工具方法快速实现,代码更简洁:

const _ = require('lodash');

const items = [ 
  {item_id:1,quantity:5}, 
  {item_id:1,quantity:10}, 
  {item_id:2,quantity:45}, 
  {item_id:2,quantity:30}, 
  {item_id:2,quantity:20}, 
  {item_id:3,quantity:10}, 
];

const groupedItems = _.chain(items)
  .groupBy('item_id') // 按item_id分组
  .map((group, itemId) => ({
    item_id: parseInt(itemId), // 把字符串键转回数字
    quantity: _.sumBy(group, 'quantity') // 汇总每组的quantity
  }))
  .value();

console.log(groupedItems);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:51:53