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

React.js计算各对象数组总价并渲染到表格单元格方法

实现方案

你只需要在遍历每一组商品时,累加组内所有商品的totalPrice得到分组合计值,直接填入对应空的<td>单元格即可,计算结果和你预期的405、198、336完全一致。

核心计算逻辑

对每个内层商品分组数组,用reduce方法做累加即可:

// items为当前遍历到的内层商品数组
const groupTotal = items.reduce((sum, item) => sum + item.totalPrice, 0)

修改后的完整表格代码

代码里补了React列表渲染要求的key属性,避免控制台抛出渲染警告:

<table className='table'>
  <thead>
    <tr>
      <th scope='col'>Items</th>
      <th scope='col'>Total Items Price</th>
    </tr>
  </thead>
  <tbody>
    {cardItems.map((items, groupIndex) => (
      <tr key={groupIndex}>
        <td>
          {items.map((item, itemIndex) => (
            <React.Fragment key={itemIndex}>
              <b className='mc-red'>{item.title}</b> Item Price:{' '}
              {item.price} LE, Item Count: {item.count}, Item Total Price:{' '}
              {item.totalPrice} LE
              <br />
            </React.Fragment>
          ))}
        </td>
        <td>
          {items.reduce((sum, item) => sum + item.totalPrice, 0)} LE
        </td>
      </tr>
    ))}
  </tbody>
</table>

渲染效果

表格三行的总价列会按顺序展示:

  • 第一组(McRoyale、Big Mac):405 LE
  • 第二组(Double Big Tasty):198 LE
  • 第三组(Grand Chicken Premier、Spicy Chicken Fillet):336 LE
    完全匹配预期要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 17:21:22