To iterate over keys in a map in JavaScript, you can use the keys method or a for...of loop. This allows you to access each key in the map.
We can iterate over keys in a map in JavaScript using a for...of loop with the keys method, which provides a convenient syntax for iterating over all keys in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.keys
method to get an iterable of the keys in the map.console.log
function to verify that we are iterating over all keys.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Iterate over keys using for...of loop
for (const key of myMap.keys()) {
console.log(key);
}
one two three
We can iterate over keys in a map in JavaScript using the forEach method, which provides a flexible way to access each key in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.forEach
method to iterate over the key-value pairs in the map.forEach
, we access each key.console.log
function to verify that we are iterating over all keys.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Iterate over keys using forEach method
myMap.forEach((value, key) => {
console.log(key);
});
one two three
We can store keys in a separate array and then iterate over the array in JavaScript, which provides a way to work with keys independently of their values.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.keys
to store the keys from the map.keys
method to get an iterable of the keys in the map and spread it into the keys
array using the spread operator.keys
array and print each key to the console using the console.log
function to verify that we have stored all keys separately.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Store keys in a separate array
const keys = [...myMap.keys()];
// Iterate over the keys array
for (const key of keys) {
console.log(key);
}
one two three
In this tutorial, we learned How to Iterate Over Keys in a Map in JavaScript language with well detailed examples.