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

89
Visualizações
Iterating over Map object

I'm new to javascript and I'm trying to understand how to use the Map feature. I have an array of numbers, and if the value is 0, I want the key of the object to be false, and for any other value; true.

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

0

Welcome to stackoverflow! What you need to know is that a key is unique in a map object. You have only two keys which are true and false. So, if you try to insert into the map a key that already exists, then it will be updated with the new key/value pair you are setting. This is why you only see two key/value pairs as output. Also as a little side-note when you declare values of array1 since you are working with a single element in each iteration of the loop it would be better to have value of array1 to make the code a little more cleaner.

about 4 years ago · Juan Pablo Isaza Relatório

0

Since map key is unique, so you got only two keys. If you want to get maps for each values, you can make a pair of key and value and then insert it into an array.

const array1 = [1,0,1,0,1,-1];

let result = [];
for (values of array1 ) {
    if (values !== 0) {
        const mapExample = new Map(); 
        mapExample.set(true, values)
        result.push(mapExample)
    } else {
        const mapExample = new Map(); 
        mapExample.set(false, values)
        result.push(mapExample)
    }
}

console.log(result)

the result would be like this

[
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { true => -1 }
]
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