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

392
Visualizações
Set a ES6 Map from an array of objects in Typescript?

I have an array of objects like such...

const myObjects: MyObjects[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];

I want to set this data into a Map based on id.

The way I have now is a forEach loop, but is there a simpler way or a method I am missing on the Map type ? I find myself doing this over and over again and thinking must be a simpler way.

i.e

const myMap = new Map<number, MyObject>();
myObjects.forEach(obj => {
  myMap.set(obj.id, obj);
});

I want to move them to a Map so they are easier to access by id versus iterating over the whole array.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Is there a simpler way or a method I am missing on the Map type?

"Simple" is a bit subjective. I usually use this approach because it fits in one line and because initializing a Map with some elements might be faster than initializing it and then adding elements.

const myObjects: { id: number; data: string; }[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];
const myMap = new Map(myObjects.map(obj => [obj.id, obj]));

Explanation: The Map constructor takes an itrerable of iterables (in this case an array of arrays) as the first parameter. Each element in the main array is an entry in the map, with the key being the element's first element and the value being the element's second element.

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