Simon Gaviria
Simon Gaviria

Reputation: 13

Converting an Array of Objects to an Object of arrays

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

Answers (2)

Lafi
Lafi

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

CertainPerformance
CertainPerformance

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

Related Questions