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']}
]
我尝试过,但不知道怎么做。 感谢您的帮助。
您可以使用以下代码:
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);