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

React中如何按created_at日期计算对象列表的item_subtotal_amount总和

按日期计算item_subtotal_amount总和的实现方法

首先要明确:你当前的test是单个对象,无法使用forEach循环,实际业务中你应该是拥有多个此类对象组成的数组(比如命名为orders),以下是针对数组场景的解决方案:

核心思路

  1. 统一日期格式:提取created_at中的YYYY-MM-DD部分,避免时间部分干扰日期比较
  2. 筛选+求和:可以通过filter+reduce组合实现,或直接用reduce一步完成(减少数组遍历次数,效率更高)

代码实现

1. 准备示例数组(模拟你的业务数据)

const orders = [
  {"id": 1414,"item_subtotal_amount": 3795,"created_at": "2022-12-19T23:02:25+00:00"},
  {"id": 1415,"item_subtotal_amount": 2500,"created_at": "2022-12-19T10:15:30+00:00"},
  {"id": 1416,"item_subtotal_amount": 1800,"created_at": "2022-12-20T08:40:10+00:00"}
];

2. 高效求和方法(reduce一步完成)

function calculateDailySubtotalSum(orders, targetDate) {
  // 转换目标日期为YYYY-MM-DD格式
  const targetDateStr = targetDate.toISOString().split('T')[0];
  
  return orders.reduce((total, order) => {
    // 提取订单日期的YYYY-MM-DD部分
    const orderDateStr = order.created_at.split('T')[0];
    // 日期匹配则累加金额,否则保持原总和
    return orderDateStr === targetDateStr ? total + order.item_subtotal_amount : total;
  }, 0); // 初始总和设为0
}

// 使用示例:计算2022-12-19的订单金额总和
const targetDate = new Date('2022-12-19');
const dailyTotal = calculateDailySubtotalSum(orders, targetDate);
console.log(dailyTotal); // 输出6295(3795+2500)

3. 单个对象的特殊处理

如果确实只有单个对象,直接判断日期后取值即可:

const test = {"id": 1414,"item_subtotal_amount": 3795,"created_at": "2022-12-19T23:02:25+00:00"};
const targetDateStr = new Date('2022-12-19').toISOString().split('T')[0];
const orderDateStr = test.created_at.split('T')[0];
const total = orderDateStr === targetDateStr ? test.item_subtotal_amount : 0;
console.log(total); // 输出3795

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:25:09