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

135
Vistas
Javascript reduce array of object into one object with keys

Hello i am trying to repack array of objects and convert it into one object with specific keys. So here is array:

 const entryPenaltyGroups = [
      { entryId: 16, intervalId: 8, penaltyTime: 16000 },
      { entryId: 16, intervalId: 10, penaltyTime: 6000 }
 ]

Expected result should be:

{
   '8': {
     penaltyTime: 16000
   },
   '10': {
     penaltyTime: 6000
   }
}

I have tried something with map(), but not getting expected results.

   for (const entry of entryPenaltyGroups) {
        entry.map(x => [{
          [x.intervalId]: {
             penaltyTime: x.intervalId
          },
        }])
    }

Should i use reduce() instead maybe?

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

0

You can map the array into [key, value] pairs, and then use Object.fromEntries to convert the mapped array into a single object:

Object.fromEntries(entryPenaltyGroups.map(
    ({intervalId, penaltyTime}) => [intervalId, {penaltyTime}]
))

Alternatively:

Object.fromEntries(entryPenaltyGroups.map(
    entry => [entry.intervalId, {penaltyTime: entry.penaltyTime}]
))

If there are any duplicate keys, the last occurrence will be used in the resulting object.

about 4 years ago · Juan Pablo Isaza Denunciar

0

A solution with reduce. This will override the item if they have the same intervalId , but OP commented that this is not a problem for them

const entryPenaltyGroups = [
      { entryId: 16, intervalId: 8, penaltyTime: 16000 },
      { entryId: 16, intervalId: 10, penaltyTime: 6000 }
 ]
 
 const result = entryPenaltyGroups.reduce( (acc,cur) => {
    acc[cur.intervalId] = {penaltyTime: cur.penaltyTime};
    return acc;
 }
 ,{})
 
 
 
 console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

const entryPenaltyGroups = [
      { entryId: 16, intervalId: 8, penaltyTime: 16000 },
      { entryId: 16, intervalId: 10, penaltyTime: 6000 }
]
const formatted = {}
for(entry of entryPenaltyGroups){
      formatted[entry.intervalId] = {penaltyTime: entry.penaltyTime}
}
console.log(formatted)

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