[Vuejs]-Javascript – ES6 array function to create an object from array

1👍

Using Array#reduce to accumulate an object with the desired data. Foreach object from your array look if the accumultaed object has an entry for the lib-key (i.e. it’s not undefined). If not create it with the property event and obs (with an empty array as start). In both cases add to this array your obs-value.
To get the desired array out of this use Object#values to get rid of the outer grouping-event.

Note: I generalized your problem a little bit, so that you can have different events that will be grouped.

let arr = [
  { 
    event: "LIB",
    block_calendar: "YES",
    obs: "Lorem Ipsum",
    status: "Block",
  },
  { 
    event: "LIB",
    block_calendar: "YES",
    obs: "Ipsum Lorem",
    status: "Block"
  }
];

let result = Object.values(arr.reduce((acc, cur) => {
    if (!acc[cur.event]) 
        acc[cur.event] = {event: cur.event, obs: []};
    acc[cur.event].obs.push(cur.obs);
    return acc;
}, {}));

console.log(result);

Leave a comment