map.entries()


The map.entries() method returns a new iterator object that contains a [key, value] array for each entry in the Map. Using a for...of loop with array destructuring (for (const [key, value] of map)) is the most common way to iterate, giving you direct access to both the key and the value in each cycle. Note that for...of on a map defaults to using .entries(), so you can often omit it.

Example 1: Basic Entry Iteration

// A map of student names to their grades.
const studentGrades = new Map();
studentGrades.set('Alice', 'A');
studentGrades.set('Bob', 'C');

// Iterate over the [key, value] pairs.
// Note: map.entries() is the default, so it can be omitted.
for (const [student, grade] of studentGrades) {
  console.log(`${student} received a grade of ${grade}.`);
}

Explanation This loop uses array destructuring [student, grade] to cleanly assign the key and value of each map entry to separate variables. This is the most direct way to work with both parts of an entry simultaneously.


Example 2: Reconstructing a String

// A map representing query parameters for a URL.
const queryParams = new Map();
queryParams.set('search', 'JavaScript');
queryParams.set('page', '2');

// Build a query string from the map's entries.
let queryString = '';
for (const [key, value] of queryParams.entries()) {
  queryString += `${key}=${value}&`;
}
// Remove the trailing ampersand.
queryString = queryString.slice(0, -1); 

console.log(queryString); // Outputs: search=JavaScript&page=2

Explanation This example iterates through the map's entries to construct a URL query string. Destructuring provides easy access to both the parameter key and its value for formatting.


Example 3: Creating a New Object

// A map storing a person's profile data.
const profileMap = new Map();
profileMap.set('name', 'Diana');
profileMap.set('age', 30);
profileMap.set('isEmployed', true);

// Convert the map to a standard JavaScript object.
const profileObject = {};
for (const [key, value] of profileMap.entries()) {
  profileObject[key] = value;
}

console.log(profileObject); // { name: 'Diana', age: 30, isEmployed: true }

Explanation This code effectively transforms a Map into a plain Object. It iterates through each [key, value] pair and assigns it as a property on the newly created profileObject.


Example 4: Filtering into a New Map

// A map of inventory items and their quantities.
const inventory = new Map();
inventory.set('apples', 10);
inventory.set('bananas', 0);
inventory.set('cherries', 5);

// Create a new map containing only items that are in stock.
const inStock = new Map();
for (const [item, quantity] of inventory.entries()) {
  if (quantity > 0) {
    inStock.set(item, quantity);
  }
}

console.log(inStock.get('apples')); // 10
console.log(inStock.has('bananas')); // false

Explanation Here, we iterate through one map (inventory) to selectively populate another (inStock). The for...of loop with destructuring makes it easy to read the entry and apply a condition before setting it on the new map.


Example 5: Iterating with Mixed Data Types

// A map with keys and values of various types.
const mixedMap = new Map();
const funcKey = () => {};
mixedMap.set('a string', 123);
mixedMap.set(funcKey, { a: 1 });

// Log the type of each key and value.
for (const [key, value] of mixedMap.entries()) {
  console.log(`Key type: ${typeof key}, Value type: ${typeof value}`);
}

Explanation This example emphasizes the flexibility of Maps. The for...of loop handles entries with different data types for keys and values seamlessly, allowing you to inspect or use them as needed.


Example 6: Using entries() Explicitly

// A map of feature flags for an application.
const featureFlags = new Map();
featureFlags.set('newDashboard', true);
featureFlags.set('betaAccess', false);

// Using .entries() explicitly, which behaves the same as the default.
const iterator = featureFlags.entries();

// The iterator gives you fine-grained control if needed.
console.log(iterator.next().value); // ['newDashboard', true]
console.log(iterator.next().value); // ['betaAccess', false]

Explanation This code shows the explicit use of map.entries(). While a for...of loop is more common, directly calling the method gives you an iterator object, which can be manually advanced with the .next() method.


Example 7: Updating Values During Iteration

// A map of scores that need a bonus applied.
const scores = new Map();
scores.set('player1', 100);
scores.set('player2', 85);

// Add 10 bonus points to each player's score.
for (const [player, score] of scores.entries()) {
  scores.set(player, score + 10);
}

console.log(scores.get('player2')); // Outputs: 95

Explanation This loop iterates over the entries and, within the same loop, uses map.set() to update the value for the current key. Destructuring makes it easy to get the player's name and original score to calculate the new one.