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

如何按类别汇总JS对象数组中的支出金额并生成指定格式数组

解决类别支出汇总问题

首先你的原始代码存在两处问题:

  • transactions 应当是数组(用[]包裹),否则会触发语法错误
  • 第三个交易对象的amount和name字段写反了,正确写法应为"amount": "83", "name": "gas"

修正后的原始数据

var transactions = [
  {
    "date": "1-1-2023",
    "amount": "850",
    "name": "rent",
    "category": "housing",
    "notepad": ""
  },
  {
    "date": "1-1-2023",
    "amount": "91",
    "name": "electric",
    "category": "housing",
    "notepad": ""
  },
  {
    "date": "1-1-2023",
    "amount": "83",
    "name": "gas",
    "category": "housing",
    "notepad": ""
  },
  {
    "date": "1-1-2023",
    "amount": "50",
    "name": "car insurance",
    "category": "transportation",
    "notepad": ""
  }
];

实现类别汇总的代码

通过遍历交易数据,用对象累加各品类支出,再转换为目标数组格式:

// 初始化存储品类总支出的对象
const categoryTotals = {};

// 遍历交易数据,按品类累加金额
transactions.forEach(transaction => {
  // 将字符串金额转为数字,避免字符串拼接错误
  const amount = parseFloat(transaction.amount);
  const category = transaction.category;
  
  categoryTotals[category] = (categoryTotals[category] || 0) + amount;
});

// 转换为要求的数组格式
var groups = Object.keys(categoryTotals);
var expenses = Object.values(categoryTotals).map(total => total.toString());

// 输出结果
console.log(groups); // ['housing', 'transportation']
console.log(expenses); // ['1024', '50']

注:修正数据后housing类别的实际总和为850+91+83=1024,并非示例中的1000

代码逻辑说明

  1. 用forEach遍历每笔交易,将字符串类型的金额转为数字后,按品类累加到categoryTotals对象中
  2. Object.keys(categoryTotals)提取所有品类名称,生成groups数组
  3. Object.values(categoryTotals)提取各品类总金额,转为字符串后生成expenses数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:11:28