如何基于键对对象的JavaScript数组进行分组 [英] How to Group JavaScript Array of Object based on key

查看:45
本文介绍了如何基于键对对象的JavaScript数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样的数据

const carts = [
  {
    name: 'Voucher A',
    participants: [
      {
        date: 112
      },
      {
        date: 112
      }
    ],
    supplierName: 'ABC',
    ticketDescription: 'Description of',
    ...data
  },
  {
    name: 'Voucher B',
    participants: [
      {
        date: 111
      },
      {
        date: 112
      }
    ],
    supplierName: 'ABC',
    ticketDescription: 'Description of',
    ...data
  }
]

我想根据日期(如果它具有相同的日期)将其分组.因此,对于上述数据,预期结果将是

And I want to group it based on the date (if it has same date). So for data above, the expected result will be

expected = [
  {
    name: 'Voucher A',
    date: 1,
    count: 1,
    supplierName: 'ABC',
    ticketDescription: 'Description of',
    ...data
  },
  {
    name: 'Voucher A',
    date: 2,
    count: 1,
    supplierName: 'ABC',
    ticketDescription: 'Description of',
    ...data
  }
]

因为它有不同的日期.但是如果日期相同,则预期结果将是

Because it has different date. But if it has same date, the expected result will be

expected = [
  {
    name: 'Voucher A',
    date: 1,
    count: 2,
    supplierName: 'ABC',
    ticketDescription: 'Description of',
    ...data
  }
]

我试图使用reduce对其进行分组,但它没有给出我想要的结构

I was trying to use reduce to group it but it did not give the structure I want

carts.forEach(cart => {
  cart.participants.reduce((acc, obj) => {
    acc[obj.date] = [...acc[obj.date] || [], obj]
    return acc
  }, {})
})

推荐答案

要组织数据,我认为您需要两个关联来分组:名称​​和该名称的日期及其计数:

To organize the data, I think you need two associations to group by: the name and the dates and their counts for that name:

const carts = [
  {
    name: 'Voucher A',
    participants: [
      {
        date: 1
      },
      {
        date: 2
      }
    ]
  }
];

const groupedByNames = {};
for (const { name, participants } of carts) {
  if (!groupedByNames[name]) groupedByNames[name] = {};
  for (const { date } of participants) {
    groupedByNames[name][date] = (groupedByNames[name][date] || 0) + 1;
  }
}
const output = Object.entries(groupedByNames).flatMap(
  ([name, dateCounts]) => Object.entries(dateCounts).map(
    ([date, count]) => ({ name, date: Number(date), count })
  )
);
console.log(output);

这篇关于如何基于键对对象的JavaScript数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆