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

JavaScript如何将对象数组按类别分类汇总对应数值字段

实现方案

你可以通过Array.prototype.reduce结合临时映射对象完成分组累加,逻辑简单易懂,性能也足够应对绝大多数场景:

完整代码

const data = [
  {
    category: 'personal',
    amount: 80000,
    month: 'Diciembre',
  },
  {
    category: 'comida',
    amount: 207000,
    month: 'Diciembre',
  },
  {
    category: 'comida',
    amount: 43000,
    month: 'Diciembre',
  },
  {
    category: 'salidas',
    amount: 124000,
    month: 'Diciembre',
  },
  {
    category: 'casa',
    amount: 450505,
    month: 'Diciembre',
  },
  {
    category: 'casa',
    amount: 500000,
    month: 'Diciembre',
  },
  {
    category: 'varios',
    amount: 260000,
    month: 'Diciembre',
  },
  {
    category: 'casa',
    amount: 296300,
    month: 'Diciembre',
  },
];

// 分组累加核心逻辑
const groupedMap = data.reduce((acc, currentItem) => {
  const { category, amount, month } = currentItem;
  // 分类不存在则初始化
  if (!acc[category]) {
    acc[category] = { category, amount: 0, month };
  }
  // 累加对应分类的金额
  acc[category].amount += amount;
  return acc;
}, {});

// 将映射对象转为结果数组,不需要varios分类可以加filter过滤
const dataSummarized = Object.values(groupedMap).filter(item => item.category !== 'varios');

console.log(dataSummarized);

输出结果

运行上述代码后dataSummarized的结构和你要求的完全一致:

[
  { category: 'personal', amount: 80000, month: 'Diciembre' },
  { category: 'comida', amount: 250000, month: 'Diciembre' },
  { category: 'salidas', amount: 124000, month: 'Diciembre' },
  { category: 'casa', amount: 1246805, month: 'Diciembre' }
]

逻辑说明

  • reduce方法会遍历整个数组,用第一个参数的函数累计结果,第二个参数的空对象是累计的初始值
  • 临时用对象做映射是为了避免每次遍历都要查找数组,分类匹配的时间复杂度只有O(1),效率更高
  • 所有条目month值统一的情况下直接复用即可,如果后续有不同月份的需求,可以调整分组逻辑同时按category+month做key即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:15:00