JavaScript Map Methods
Maps provide several methods for iterating, converting, and working with key-value pairs. Understanding these methods lets you efficiently transform data between Maps, Arrays, and Objects.
forEach()
The forEach() method executes a function for each key-value pair in the Map. Note that the callback receives (value, key, map) -- the value comes first, which is different from what you might expect.
const scores = new Map([
["Alice", 95],
["Bob", 82],
["Charlie", 91],
["Diana", 88]
]);
// forEach(value, key, map)
scores.forEach((score, name) => {
console.log(`${name}: ${score}`);
});
// Use forEach to find highest score
let highest = ["", 0];
scores.forEach((score, name) => {
if (score > highest[1]) {
highest = [name, score];
}
});
console.log("Highest:", highest[0], "with", highest[1]);keys(), values(), entries()
keys() returns an iterator of all keys. values() returns an iterator of all values. entries() returns an iterator of [key, value] pairs. All maintain insertion order.
const config = new Map([
["theme", "dark"],
["lang", "en"],
["fontSize", 16]
]);
// keys()
console.log("Keys:", [...config.keys()]);
// values()
console.log("Values:", [...config.values()]);
// entries() - same as iterating the Map directly
for (const [key, value] of config.entries()) {
console.log(`${key} = ${value}`);
}
// Destructuring in for...of
for (const [key] of config) {
console.log("Key only:", key);
}Map from Array
Maps can be created from any iterable of [key, value] pairs. This includes arrays, other Maps, and the result of Object.entries().
// From array of pairs
const pairs = [["a", 1], ["b", 2], ["c", 3]];
const map1 = new Map(pairs);
console.log("From pairs:", [...map1]);
// From Object using Object.entries()
const obj = { name: "Alice", age: 25, city: "NYC" };
const map2 = new Map(Object.entries(obj));
console.log("From object:", [...map2]);
// From another Map
const map3 = new Map(map2);
console.log("From map:", [...map3]);
// From two arrays (zip)
const keys = ["x", "y", "z"];
const values = [10, 20, 30];
const map4 = new Map(keys.map((k, i) => [k, values[i]]));
console.log("Zipped:", [...map4]);Map to Array
Converting a Map to an array is useful when you need to use array methods like map(), filter(), sort(), or reduce() on Map data.
const scores = new Map([
["Alice", 95],
["Bob", 82],
["Charlie", 91]
]);
// Spread to array of pairs
const arr = [...scores];
console.log("Array of pairs:", arr);
// Array.from()
const arr2 = Array.from(scores);
console.log("Array.from:", arr2);
// Keys and values as arrays
console.log("Keys array:", [...scores.keys()]);
console.log("Values array:", [...scores.values()]);
// Filter and sort Map entries using arrays
const sorted = [...scores]
.sort((a, b) => b[1] - a[1])
.map(([name, score]) => `${name}: ${score}`);
console.log("Sorted by score:", sorted);Map to Object and Object to Map
You can convert between Maps and Objects using Object.entries() and Object.fromEntries(). Note that converting to an Object will stringify all keys.
// Object to Map
const person = { name: "Bob", age: 30, role: "Dev" };
const personMap = new Map(Object.entries(person));
console.log("Map from obj:", [...personMap]);
// Map to Object
const backToObj = Object.fromEntries(personMap);
console.log("Back to obj:", backToObj);
// Warning: non-string keys are coerced
const numMap = new Map([[1, "one"], [2, "two"]]);
const numObj = Object.fromEntries(numMap);
console.log("Keys become strings:", Object.keys(numObj));
console.log("Type of key:", typeof Object.keys(numObj)[0]);
// Practical: transform object values via Map
const prices = { apple: 1.5, banana: 0.75, cherry: 2.0 };
const discounted = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 0.9])
);
console.log("Discounted:", discounted);| Operation | Code |
|---|---|
| Map to Array | [...map] or Array.from(map) |
| Map keys to Array | [...map.keys()] |
| Map values to Array | [...map.values()] |
| Array to Map | new Map(arrayOfPairs) |
| Object to Map | new Map(Object.entries(obj)) |
| Map to Object | Object.fromEntries(map) |