Home > Software design >  How to group objects by their name
How to group objects by their name

Time:03-19

I receive a response like

   [
     {id:1,name:"type1-something"},
     {id:2,name:"something-type2"},
     {id:3,name:"type3-something"},
     {id:4,name:"something-type1"}
   ]

and I have an Enum that contains all names from the response

enum E{
  E1 = 'type1-something',
  E2 = 'something-type2',
  E3 = 'type3-something',
  E4 = 'something-type1',
}

I need to group response by their names. For example from the response above I need to transform it in

{
 "Type1" : [{id:1,name:"type1-something"},{id:4,name:"something-type1"}],
 "Type2" : [{id:2,name:"something-type2"}],
 "Type3" : [{id:3,name:"type3-something"}],
}

What approach can be taken? I think of a map and a for loop

if (object.name == E1 || object.name == E4)
   MAP['Type1'].push(object)

But I have over 30 entries in the enum and this will approach will become very big and hard to understand. Obviously I can reduce the amount of code by adding some smaller enums that will include only their type, but I wonder if there is a more obvious way that I do not see

CodePudding user response:

You could get the type and group by this value.

const
    getType = ({ name }) => name
        .match(/type\d /g)
        ?.map(s => s[0].toUpperCase()   s.slice(1))
        .join('-') || '',
    data = [{ id: 1, name: "type1-something" }, { id: 2, name: "something-type2" }, { id: 3, name: "type3-something" }, { id: 4, name: "something-type1" }, { id: 5, name: "type3-type1-something" }],
    result = data.reduce((r, o) => {
        (r[getType(o)] ??= []).push(o);
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related