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

233
Visualizações
Get specific elements of a Map in javascript

For a given map like this:

const contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})

How can I get the list of "phone"s? Something like:

console.log(contacts.getKey("phone"))

expected answer: ["213-555-1234", "617-555-4321"]

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

0

You can get the map's values with the values() method, then use .map() to extract from them.

const contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})

console.log(Array.from(contacts.values()).map(c => c.phone));

There's nothing built-in that automatically gets properties of map elements.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can directly iterate the Map object using its built-in iterator that works with a for loop. This has the advantage that it doesn't make unnecessary intermediate arrays or copies of the data. As such, it should be more efficient on larger sets of data.

const contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"});
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"});

let phoneNumbers = [];
for (let value of contacts.values()) {
    phoneNumbers.push(value.phone);
}
console.log(phoneNumbers);

Or, you could write yourself a little helper function to do this work for you, so then you can reuse the logic elsewhere:

function mapGetField(map, field) {
    let results = [];
    for (let value of map.values()) {
        results.push(value[field]);
    }
    return results;
}

const contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"});
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"});

console.log(mapGetField(contacts, "phone"));

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