如何基于对象的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
相关产品推荐
相关产品推荐

