Reputation: 13
So let's say I have an array of objects
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" }]
So for every day, there will be an array of objects. For example, day 22 should have two items in the array. So the structure to be in this format
{ 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" } ] }
using the reduce method
const arrayToObject = (array) =>array.reduce((obj, item) => {
obj[item.event_day] = [item]
return obj}, {})
arrayToObject(data)
gives me the following output:
{ 22: [ { description: 'my second event',
start_time: '11:00',
end_time: '12:00',
event_day: '22' } ] }
This only adds the last item to the array. Is there a way to add all another objects to the array?
Upvotes: 0
Views: 108
Reputation: 1342
this should work also:
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);
Upvotes: 0
Reputation: 370659
If the array corresponding to the event_day
doesn't exist in the accumulator object, create it first, and then push
to it:
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);
Upvotes: 3