for...of with map.keys()


JavaScript Maps are iterable, meaning you can easily loop through their contents. The for...of loop is the standard way to iterate, and Maps provide specific methods (.keys(), .values(), .entries()) to control which part of the key-value pair you want to access during each iteration.

for...of with map.keys()

The map.keys() method returns a new iterator object that contains the keys for each element in the Map in insertion order. You can use a for...of loop to cycle through this iterator, accessing each key one by one.

Example 1: Basic Key Iteration

// A map of project names and their completion status.
const projectStatus = new Map();
projectStatus.set('Project Alpha', 'Complete');
projectStatus.set('Project Beta', 'In Progress');

// Iterate over the keys of the map.
for (const project of projectStatus.keys()) {
  // Log each project name (the key).
  console.log(project);
}

Explanation This code creates a simple for...of loop to go through the projectStatus map. The map.keys() method ensures that the loop variable project is assigned the key of each entry on every iteration.


Example 2: Iterating Numeric Keys

// A map using product IDs (numbers) as keys.
const productCatalog = new Map();
productCatalog.set(404, 'Keyboard');
productCatalog.set(501, 'Mouse');

// Loop through just the product IDs.
console.log('Available Product IDs:');
for (const id of productCatalog.keys()) {
  // Print each numeric key.
  console.log(id);
}

Explanation This example demonstrates that map.keys() works perfectly with non-string keys, such as numbers. The loop iterates over the numeric product IDs, which can then be used to perform other operations.


Example 3: Collecting Keys into an Array

// A map storing user roles.
const userRoles = new Map();
userRoles.set('admin', 'Full Access');
userRoles.set('editor', 'Create/Edit Content');
userRoles.set('viewer', 'Read-Only');

// Use the spread syntax with .keys() to create an array of keys.
const roles = [...userRoles.keys()];

// The 'roles' constant is now an array of the map's keys.
console.log(roles); // Outputs: ['admin', 'editor', 'viewer']

Explanation Instead of a for...of loop, this snippet uses the spread syntax (...) on the keys() iterator. This provides a concise, one-line method for extracting all map keys into a new array.


Example 4: Checking Permissions

// A map defining access levels for different user types.
const permissions = new Map();
permissions.set('guest', false);
permissions.set('user', true);
permissions.set('admin', true);

// Iterate through the keys to identify who has access.
for (const role of permissions.keys()) {
  // Check the value associated with the key to see if they have access.
  if (permissions.get(role) === true) {
    console.log(`${role} has access.`);
  }
}

Explanation Here, the loop iterates over the keys (role), and inside the loop, we use permissions.get(role) to retrieve the corresponding value. This pattern is useful when you need to make a decision based on the key itself.


Example 5: Iterating with Object Keys

// A map using objects as keys to store metadata about them.
const elementMetadata = new Map();
const buttonA = { id: 'submit-btn' };
const buttonB = { id: 'cancel-btn' };
elementMetadata.set(buttonA, 'Main action');
elementMetadata.set(buttonB, 'Secondary action');

// Iterate over the object keys.
for (const element of elementMetadata.keys()) {
  // Log the id of each object key.
  console.log(`Element ID: ${element.id}`);
}

Explanation This example showcases a powerful feature of Maps: using objects as keys. The for...of loop with .keys() iterates through these object keys, which retain their reference and properties.


Example 6: Logging Configuration Keys

// A map for storing application settings.
const appConfig = new Map();
appConfig.set('apiKey', 'xyz123');
appConfig.set('theme', 'dark');
appConfig.set('version', '2.5.1');

// Loop through and log all the configuration setting names.
console.log('Application Settings:');
for (const setting of appConfig.keys()) {
  console.log(`- ${setting}`);
}

Explanation This practical example shows how to iterate over the keys of a configuration map. This can be used to display all available settings to a user or for debugging purposes.


Example 7: Filtering Keys

// A map of tasks and their status.
const tasks = new Map();
tasks.set('Write report', 'done');
tasks.set('Fix bug #101', 'active');
tasks.set('Deploy update', 'pending');
tasks.set('Fix bug #205', 'active');

// Find all keys that represent an active bug.
const activeBugKeys = [];
for (const taskName of tasks.keys()) {
  if (taskName.includes('bug') && tasks.get(taskName) === 'active') {
    activeBugKeys.push(taskName);
  }
}
console.log('Active Bugs:', activeBugKeys);

Explanation This code iterates through all task keys. It then applies a condition to both the key name (checking for 'bug') and its corresponding value to filter and collect only the relevant keys.