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