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"]
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"))
Share Improve this question asked Feb 23, 2022 at 18:28 Luís Felipe KunzlerLuís Felipe Kunzler 333 silver badges8 bronze badges 4expected answer: ["213-555-1234", "617-555-4321"]
-
1
The keys of the Map are
Jessie
andHilary
. – Barmar Commented Feb 23, 2022 at 18:29 - 1 It doesn't make sense to use a map keyed by name if you want to get all phone numbers, you'd have to loop over every item. – nanobar Commented Feb 23, 2022 at 18:29
- 1 yes, but without iterating with the keys, can I get the elements? – Luís Felipe Kunzler Commented Feb 23, 2022 at 18:30
- 1 No you would need to loop – nanobar Commented Feb 23, 2022 at 18:31
2 Answers
Reset to default 4You 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.
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"));