Skip to content
Advertisement

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”]

Advertisement

Answer

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"));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement