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?
obj[item.event_day]already exists.