In this article we will learn how to loop through map values.
It is very common to loop through map values in JavaScript.
Problem
Now we have a problem, which is that we want to iterate over the values in the map
Imagine we have a map like this:
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
And we want to iterate over the map values, to get this result:
John
30
true
How to solve this problem?
The solution is easy, because there is already a function that returns a new iterator object that contains the values for each element
Solution:
First we have to get all the values in iterator object.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get values
const values = map.values();
// Result:
console.log(values);
Output
[Map Iterator] { 'John', 30, true }
Now we have to convert the object into an array, and here we will use the Array.from
method.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get values
const values = map.values();
// Convert values to array
const toArray = Array.from(values);
// Result
console.log(toArray);
Output
[ 'John', 30, true ]
Now the rest of the solution has become easy, which is to iterate over the array in any possible way
Iterate using forEach
.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get values
const values = map.values();
// Convert to array
const toArray = Array.from(values);
// Iterate over values
toArray.forEach(value => {
console.log(value);
});
Result:
John
30
true
Yay 🚀🚀!
We can also iterate over elements using for
.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get values
const values = map.values();
// Convert to array
const toArray = Array.from(values);
// Iterate using `for`
for (let i = 0; i < toArray.length; i++) {
console.log(toArray[i]);
}
Result:
John
30
true
Thank you for reading
Thank you for reading my blog. 🚀