Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group objects in an array by Id - JavaScript

I have an object array that has two fields id, and the type of action permission

const array=[
{view: false, id: 1},
{create: false, id: 1},
{read: false, id: 1},
{update: false, id: 1},
{delete: false, id: 1},
{view: false, id: 2},
{create: false, id: 2},
{read: false, id: 2},
{update: false, id: 2},
{delete: false, id: 2},
]

I want to convert this in to the following array:

const permissions=[
{
id: 1,
view: false,
read: false,
create: false,
delete:false,
update:false
},
{
id: 2,
view: false,
read: false,
create: false,
delete:false,
update:false
}
]
like image 948
user16488183 Avatar asked Feb 05 '26 16:02

user16488183


1 Answers

You can iterate over the array using Array#reduce while updating a Map where the id is the key and its resulting object is the value.

In the end, you would have the grouped objects per id as the values in this map:

const array = [
  {view: false, id: 1},
  {create: false, id: 1},
  {read: false, id: 1},
  {update: false, id: 1},
  {delete: false, id: 1},
  {view: false, id: 2},
  {create: false, id: 2},
  {read: false, id: 2},
  {update: false, id: 2},
  {delete: false, id: 2},
];

const res = [...
  array.reduce((map, { id, ...elem }) =>
    map.set(id, { ...(map.get(id) || { id }), ...elem })
  , new Map)
  .values()
];

console.log(res);
like image 115
Majed Badawi Avatar answered Feb 08 '26 14:02

Majed Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!