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

按日期合并两个数据集并计算总金额的技术实现需求

数据集合并与金额计算实现

原始数据集

第一个集合

[
   {
      "dateTime": "10/01/2022",
      "gc": 0,
      "credit": 20,
      "debit": 1000,
      "voucher": 0,
      "e_gift": 0,
      "cash": 3000
    }, 
    {
      "dateTime": "10/02/2022",
        "gc": 0,
        "credit": 10,
        "debit": 10,
        "voucher": 0,
        "e_gift": 0,
        "cash": 100
    }
]

第二个集合

[
    {
         "dateTime": "10/01/2022",
         "Gross Total": 6000,
         "Discount": 300
      },
      {
           "dateTime": "10/02/2022",
           "Gross Total": 4000,
           "Discount": 100
       }
]

需求说明

  • 按dateTime字段将两个数据集合并,保留所有原始字段
  • 计算第一个集合中gc、credit、debit、voucher、e_gift、cash字段的数值总和,再加上第二个集合中的Gross Total,得到新字段total amount

实现方案(JavaScript)

// 定义原始数据集
const firstCollection = [
   {
      "dateTime": "10/01/2022",
      "gc": 0,
      "credit": 20,
      "debit": 1000,
      "voucher": 0,
      "e_gift": 0,
      "cash": 3000
    }, 
    {
      "dateTime": "10/02/2022",
        "gc": 0,
        "credit": 10,
        "debit": 10,
        "voucher": 0,
        "e_gift": 0,
        "cash": 100
    }
];

const secondCollection = [
    {
         "dateTime": "10/01/2022",
         "Gross Total": 6000,
         "Discount": 300
      },
      {
           "dateTime": "10/02/2022",
           "Gross Total": 4000,
           "Discount": 100
       }
];

// 将第二个集合转为以dateTime为键的映射,提升匹配效率
const secondMap = secondCollection.reduce((acc, item) => {
    acc[item.dateTime] = item;
    return acc;
}, {});

// 合并数据集并计算total amount
const mergedResult = firstCollection.map(item => {
    const matchedItem = secondMap[item.dateTime];
    const sumOfFields = item.gc + item.credit + item.debit + item.voucher + item.e_gift + item.cash;
    return {
        ...item,
        ...matchedItem,
        "total amount": sumOfFields + matchedItem["Gross Total"]
    };
});

console.log(JSON.stringify(mergedResult, null, 2));

最终输出结果

[
  {
    "dateTime": "10/01/2022",
    "gc": 0,
    "credit": 20,
    "debit": 1000,
    "voucher": 0,
    "e_gift": 0,
    "cash": 3000,
    "Gross Total": 6000,
    "Discount": 300,
    "total amount": 10020
  },
  {
    "dateTime": "10/02/2022",
    "gc": 0,
    "credit": 10,
    "debit": 10,
    "voucher": 0,
    "e_gift": 0,
    "cash": 100,
    "Gross Total": 4000,
    "Discount": 100,
    "total amount": 4120
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:35:28