所以说我有一个对象数组
const data = [{ description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" }, { description: "my second event", start_time: "11:00", end_time: "12:00", event_day: "22" }]
因此,每天都会有一系列对象。例如,第22天应该在数组中有两个项目。因此,结构必须采用这种格式
{ 22: [ { description: 'my second event',
start_time: '11:00',
end_time: '12:00',
event_day: '22' }, { description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" } ] }
使用reduce方法
const arrayToObject = (array) =>array.reduce((obj, item) => {
obj[item.event_day] = [item]
return obj}, {})
arrayToObject(data)
提供以下输出:
{ 22: [ { description: 'my second event',
start_time: '11:00',
end_time: '12:00',
event_day: '22' } ] }
这只会将最后一项添加到数组中。有没有一种方法可以将所有其他对象添加到数组?
答案 0 :(得分:3)
如果与event_day
相对应的数组在累加器对象中不存在,请首先创建它,然后再对其进行push
:
const data = [{ description: "my frist event", start_time: "11:00", end_time: "12:00", event_day: "22" }, { description: "my second event", start_time: "11:00", end_time: "12:00", event_day: "22" }];
const groupedByDay = data.reduce((a, item) => {
const { event_day } = item;
if (!a[event_day]) a[event_day] = [];
a[event_day].push(item);
return a;
}, {});
console.log(groupedByDay);
答案 1 :(得分:0)
这也应该起作用:
const data = [
{
description: 'my frist event',
start_time: '11:00',
end_time: '12:00',
event_day: '22',
},
{
description: 'my second event',
start_time: '11:00',
end_time: '12:00',
event_day: '22',
},
{
description: 'my second event',
start_time: '11:00',
end_time: '12:00',
event_day: '55',
},
];
const reduced = data.reduce(
(acc, item) => ({
...acc,
[item.event_day]: data.filter((i) => i.event_day === item.event_day),
}),
{}
);
console.log('reduced', reduced);