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

如何基于对象的paymentDate值动态分组对象集合

根据paymentDate分组对象数组的实现方案

需求说明

给定一个包含指定结构的对象数组,需要按paymentDate字段对数组元素进行分组,最终生成以paymentDate值为键、对应分组对象数组为值的结构,且逻辑需适配包含大量不同paymentDate的大规模数据场景。

原始输入数据

[
  {
    "id":29751,
    "refId":20293494,
    "pCode":712,
    "paymentDate":140101,
    "title":"Sample title",
    "heading":"A heading",
    "value":4214000,
    "remainder":429740000,
    "createdAt":"2023-01-31T07:34:29.000Z"
  },
  {
    "id":29752,
    "refId":20293495,
    "pCode":712,
    "paymentDate":140102,
    "title":"Sample title",
    "heading":"A heading",
    "value":4214000,
    "remainder":429740000,
    "createdAt":"2023-01-31T07:34:29.000Z"
  },
  {
    "id":29753,
    "refId":20293496,
    "pCode":712,
    "paymentDate":140103,
    "title":"Sample title",
    "heading":"A heading",
    "value":4214000,
    "remainder":429740000,
    "createdAt":"2023-01-31T07:34:29.000Z"
  }
]

目标输出结构

{
  "140101":[
    {
      "id":29751,
      "refId":20293494,
      "pCode":712,
      "paymentDate":140101,
      "title":"Sample title",
      "heading":"A heading",
      "value":4214000,
      "remainder":429740000,
      "createdAt":"2023-01-31T07:34:29.000Z"
    }
  ],
  "140102":[
    {
      "id":29752,
      "refId":20293495,
      "pCode":712,
      "paymentDate":140102,
      "title":"Sample title",
      "heading":"A heading",
      "value":4214000,
      "remainder":429740000,
      "createdAt":"2023-01-31T07:34:29.000Z"
    }
  ],
  "140103":[
    {
      "id":29753,
      "refId":20293496,
      "pCode":712,
      "paymentDate":140103,
      "title":"Sample title",
      "heading":"A heading",
      "value":4214000,
      "remainder":429740000,
      "createdAt":"2023-01-31T07:34:29.000Z"
    }
  ]
}

实现方案

使用JavaScript的Array.prototype.reduce()方法实现,该方法遍历数组一次即可完成分组,时间复杂度为O(n),适合处理大规模数据:

function groupByPaymentDate(arr) {
  return arr.reduce((acc, current) => {
    const key = current.paymentDate.toString();
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(current);
    return acc;
  }, {});
}

使用示例

// 原始数据数组
const data = [/* 放入原始输入数据 */];
// 执行分组
const groupedData = groupByPaymentDate(data);
// 输出结果
console.log(groupedData);

该逻辑会自动识别所有不同的paymentDate值,无需硬编码具体日期,完全适配动态数据场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:45:23