In this article we will learn how to loop through map keys.
It is very common to loop through map keys in JavaScript.
Problem
Now we have a problem, which is that we want to iterate over the keys 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 keys, to get this result:
name
age
isMarried
How to solve this problem?
The solution is easy, because there is already a function that returns a new iterator object that contains the keys for each element
Solution:
First we have to get all the keys in iterator object.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get Keys
const keys = map.keys();
// Result:
console.log(keys);
Output
[Map Iterator] { 'name', 'age', 'isMarried' }
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 Keys
const keys = map.keys();
// Convert keys to array
const toArray = Array.from(keys);
// Result
console.log(toArray);
Output
[ 'name', 'age', 'isMarried' ]
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 Keys
const keys = map.keys();
// Convert to array
const toArray = Array.from(keys);
// Iterate over keys
toArray.forEach(key => {
console.log(key);
});
Result:
name
age
isMarried
Yay 🚀🚀!
We can also iterate over elements using for
.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
['isMarried', true]
]);
// Get Keys
const keys = map.keys();
// Convert to array
const toArray = Array.from(keys);
// Iterate using `for`
for (let i = 0; i < toArray.length; i++) {
console.log(toArray[i]);
}
Result:
name
age
isMarried
Thank you for reading
Thank you for reading my blog. 🚀