You need to enable JavaScript to run this app. Reactjs新手求助:如何按姓名分组计算列表中的金额总和
优惠活动
大模型
产品
解决方案
定价
更多

Reactjs新手求助:如何按姓名分组计算列表中的金额总和

React 实现按姓名分组求和的表格展示

实现步骤

1. 整理原始数据结构

先把零散的表格类业务数据转成JS可遍历的对象数组,方便后续处理:

// 原始业务数据
const rawBusinessList = [
  { name: "Poorna", amount: 11000.00 },
  { name: "Kumar", amount: 2900.00 },
  { name: "Ashok", amount: 20000.00 },
  { name: "Kumar", amount: 3020.00 },
  { name: "Poorna", amount: 15000.00 }
]

2. 实现分组求和核心逻辑

用原生JS的reduce方法做聚合,不需要引入额外第三方依赖,逻辑清晰可复用:

/**
 * 按姓名字段分组、累计金额
 * @param {Array} list 原始业务列表
 * @returns {Array} 去重后的每人总金额列表
 */
function calculateTotalByName(list) {
  const amountMap = list.reduce((acc, currentItem) => {
    // 累加器中存在当前姓名时直接叠加金额,不存在时初始化金额为当前值
    acc[currentItem.name] = (acc[currentItem.name] || 0) + currentItem.amount
    return acc
  }, {})

  // 将聚合后的对象转回数组结构,统一保留两位小数的金额格式
  return Object.entries(amountMap).map(([name, totalAmount]) => ({
    name,
    amount: totalAmount.toFixed(2)
  }))
}

3. 封装可渲染的React组件

把处理逻辑和表格渲染结合,输出和需求一致的表格内容:

import React from 'react'

// 原始业务数据(实际项目中可替换为接口返回的数据)
const rawBusinessList = [
  { name: "Poorna", amount: 11000.00 },
  { name: "Kumar", amount: 2900.00 },
  { name: "Ashok", amount: 20000.00 },
  { name: "Kumar", amount: 3020.00 },
  { name: "Poorna", amount: 15000.00 }
]

function calculateTotalByName(list) {
  const amountMap = list.reduce((acc, currentItem) => {
    acc[currentItem.name] = (acc[currentItem.name] || 0) + currentItem.amount
    return acc
  }, {})

  return Object.entries(amountMap).map(([name, totalAmount]) => ({
    name,
    amount: totalAmount.toFixed(2)
  }))
}

export default function AmountSummaryTable() {
  // 渲染前先对原始数据做聚合处理
  const summaryList = calculateTotalByName(rawBusinessList)

  return (
    <table style={{ borderCollapse: "collapse", width: "320px" }}>
      <thead>
        <tr>
          <th style={tableHeaderStyle}>Name</th>
          <th style={tableHeaderStyle}>Amount</th>
        </tr>
      </thead>
      <tbody>
        {summaryList.map((rowData) => (
          <tr key={rowData.name}>
            <td style={tableCellStyle}>{rowData.name}</td>
            <td style={tableCellStyle}>{rowData.amount}</td>
          </tr>
        ))}
      </tbody>
    </table>
  )
}

// 抽离通用表格样式,减少重复代码
const tableHeaderStyle = {
  border: "1px solid #e5e7eb",
  padding: "10px",
  textAlign: "left"
}
const tableCellStyle = {
  border: "1px solid #e5e7eb",
  padding: "10px"
}

新手注意事项

  • 列表渲染的key值直接使用去重后的name字段即可,不会出现React提示的重复key报错
  • 金额统一用toFixed(2)处理,保证输出格式和需求中的两位小数一致
  • 整个实现无第三方依赖,复制即可运行,后续如果数据从接口拉取,只需要把返回值调整为对应对象数组结构,处理逻辑不需要改动
  • 最终聚合后的结果完全匹配预期:Poorna 累计26000.00、Kumar累计5920.00、Ashok累计20000.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 07:06:03