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

183
Visualizações
javascript: create dictionary from array of key-values objects

I have an array of objects.

const ar = [ {0 : "A"}, {1 : "B"}];

I want to create an dictionary from it

const di =  {0 : "A", 1 : "B"};

I am a little struggling with this conversion. How it is possible to do it using map or reduce?

const di = ar.map( ob => (???) }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should use reduce here instead of map. map will give you an array of objects but what you need is an object will all keys. So reduce is the best tool for it.

Main difference between map and reduce

const ar = [{ 0: "A" }, { 1: "B" }];
const di = { 0: "A", 1: "B" };

const result = ar.reduce((acc, curr) => {
  Object.keys(curr).forEach((k) => (acc[k] = curr[k]));
  return acc;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

A simple reduce can be used to merge all objects. Be aware that the keys need to be unique otherwise you will overwrite them.

The merging is done with the spread syntax

const ar = [{0 : "A"}, {1 : "B"}];

const di = ar.reduce((acc, obj) => ({...acc, ...obj}));

console.log(di);

Another simple approach is the use of Object.assign

const ar = [{0 : "A"}, {1 : "B"}];

const di = Object.assign({}, ...ar);

console.log(di);

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