JavaScript - Map Methods Part 4: Iterating Through a Map
1. keys() Method
The keys() method returns an iterator containing all the keys.
Example:
for (let key of planets.keys()) {
console.log(key);
}
// Output:
// Earth
// Mars
2. values() Method
The values() method returns an iterator containing all the values.
Example:
for (let value of planets.values()) {
console.log(value);
}
// Output:
// Third Planet
// Fourth Planet
3. entries() Method
The entries() method returns an iterator containing all key-value pairs as arrays.
Example:
for (let [key, value] of planets.entries()) {
console.log(`${key}: ${value}`);
}
// Output:
// Earth: Third Planet
// Mars: Fourth Planet
4. Iteration with forEach()
The forEach() method executes a function for each key-value pair.
Example:
planets.forEach((value, key) => {
console.log(`${key} => ${value}`);
});
// Output:
// Earth => Third Planet
// Mars => Fourth Planet