Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda