Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

68
Vistas
How to group objects by their name

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda