我想用一些 JavaScript ES6 来制作这样的对象

问题描述 投票:0回答:1
const arr=[
{date: '2024/02/05', price: '1400'}, 
{date: '2024/02/06', price: '1400'}, 
{date: '2024/02/07', price: '2000'}, 
{date: '2024/02/08', price: '2000'}, 
{date: '2024/02/09', price: '2000'}, 
{date: '2024/02/10', price: '2500'}, 
{date: '2024/02/11', price: '2500'}
]

我有一个对象数组。我想创建一个如下所示的新对象数组。

const arr=[
{price: '1400',date:['2024/02/05','2024/02/06']}, 
{price: '2000',date:['2024/02/07','2024/02/08','2024/02/09']},
{price: '2500',date:['2024/02/10','2024/02/11']}
]

我尝试过,但不知道怎么做。 感谢您的帮助。

javascript arrays reduce
1个回答
0
投票

您可以使用以下代码:

const arr = [
  { date: '2024/02/05', price: '1400' },
  { date: '2024/02/06', price: '1400' },
  { date: '2024/02/07', price: '2000' },
  { date: '2024/02/08', price: '2000' },
  { date: '2024/02/09', price: '2000' },
  { date: '2024/02/10', price: '2500' },
  { date: '2024/02/11', price: '2500' }
];

const groupedArr = arr.reduce((acc, obj) => {
  const existingItem = acc.find(item => item.price === obj.price);
  if (existingItem) {
    existingItem.date.push(obj.date);
  } else {
    acc.push({ price: obj.price, date: [obj.date] });
  }
  return acc;
}, []);

console.log(groupedArr);

© www.soinside.com 2019 - 2024. All rights reserved.