具有ID和日期的对象数组中的嵌套分组?

问题描述

我有一个json对象数组

[
  {
    "businessId": "7ab43023-7f40-40cf-b97c-563223bb27ef","id": "38fe3c68-e6aa-4c57-b4d7-dc6c4f597269","journalDate": "2020-08-13T00:00:00.000Z","transactionId": "146","accountId": "4","amount": 85,"isReconciled": 0,"active": 1,"createdAt": "2020-08-14T02:55:43.988Z","updatedAt": "2020-08-14T02:55:43.988Z"
  },{
    "id": "45bf4792-c5a5-44ed-b7e8-57557c4f30ee","transactionId": "160","amount": 70,{
    "id": "5fe82eb0-17cc-4a08-97cf-0291b4b2b740","transactionId": "158","amount": 274.5,{
    "id": "6690f228-35c1-4ba7-a0ff-a3e6a64cbc88","journalDate": "2020-06-30T00:00:00.000Z","transactionId": "151","amount": -100,{
    "id": "89a0e960-943d-4f0a-a81c-44d1ec27de59","journalDate": "2020-05-31T00:00:00.000Z","transactionId": "153","amount": -60,"updatedAt": "2020-08-14T02:55:43.988Z"
  }
]

现在我想将同一帐户ID的数据分组一年。例如

{
  "accountId": "4","Jan": [
    {
      "businessId": "7ab43023-7f40-40cf-b97c-563223bb27ef","journalDate": "2020-01-13T00:00:00.000Z","updatedAt": "2020-08-14T02:55:43.988Z"
    }
  ],"Feb": [
    {
      "businessId": "7ab43023-7f40-40cf-b97c-563223bb27ef","journalDate": "2020-02-13T00:00:00.000Z","updatedAt": "2020-08-14T02:55:43.988Z"
    }
  ]
}

请指导我如何实现此目标?

解决方法

对项目使用forEach,并使用键和accountId构建对象(每个月都有单独的存储桶)。从刚刚构建的对象中获取Object.values

const transform = (arr) => {
  const all = {};
  arr.forEach(({ accountId,journalDate,...rest }) => {
    if (!all[accountId]) {
      all[accountId] = { accountId };
    }
    const month = new Date(journalDate)
      .toDateString()
      .split(" ")[1];
    if (!all[accountId][month]) {
      all[accountId][month] = [];
    }
    all[accountId][month].push({ accountId,...rest });
  });
  return Object.values(all);
};

const data = [
  {
    businessId: "7ab43023-7f40-40cf-b97c-563223bb27ef",id: "38fe3c68-e6aa-4c57-b4d7-dc6c4f597269",journalDate: "2020-08-13T00:00:00.000Z",transactionId: "146",accountId: "4",amount: 85,isReconciled: 0,active: 1,createdAt: "2020-08-14T02:55:43.988Z",updatedAt: "2020-08-14T02:55:43.988Z",},{
    id: "45bf4792-c5a5-44ed-b7e8-57557c4f30ee",transactionId: "160",amount: 70,{
    id: "5fe82eb0-17cc-4a08-97cf-0291b4b2b740",transactionId: "158",amount: 274.5,{
    id: "6690f228-35c1-4ba7-a0ff-a3e6a64cbc88",journalDate: "2020-06-30T00:00:00.000Z",transactionId: "151",amount: -100,{
    id: "89a0e960-943d-4f0a-a81c-44d1ec27de59",journalDate: "2020-05-31T00:00:00.000Z",transactionId: "153",amount: -60,];

console.log(transform(data));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...