Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda