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

183
Vistas
Merging the contents of my array into one object

I have an array of several objects

array1 =[ {1:Eat},{2:Shower},{3:Shave}]

I want to convert this array into a single object

object1 ={1:Eat, 2:Shower, 3:Shave}

How do I go about it. The keys(1,2,3) are unique

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

0

THE SOLUTION

array.reduce((a, v) => Object.assign(a,v), {})

THE EXPLANATION

Array.reduce() loops throw the initial array aimed to "reduce" it into a single object. The reduce method allows you to store the return value of each of your iterations. It requires an initial value which in this case it will be the empty object {} that we will be filling up with our array.

Then we use Object.assign(target, source) which concatenates two objects together returning the concatenated object which in this case it will saved into our accumulator and be used as a target for the next iteration giving you when it finishes the constructed final object. As you have objects as the keys of the array, each single property Object(source) will be "assigned" to a master one (target) that will be collecting all of them into one.

array1 =[ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
obj1 = array1.reduce((a, v) => Object.assign(a,v), {})
console.log(obj1)

about 4 years ago · Juan Pablo Isaza Denunciar

0

The easiest way to achieve this is to reduce the list of objects into a single object.

const
  input = [{ 1: 'Eat' }, { 2: 'Shower' }, { 3: 'Shave' }],
  output = input.reduce((acc, obj) => ({ ...acc, ...obj }), {});

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

fromEntries and a flatMap seems to do the trick nicely

const array1 = [ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
const obj1 = Object.fromEntries(array1.flatMap(item => Object.entries(item)))

console.log(obj1)

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