The keys() method of the Map object in JavaScript returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
The syntax of Map.keys() method is:
keys()
This keys() method of Map returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
Map.keys() returns value of type Iterator
.
In JavaScript, we can use the keys()
method to get an iterator object and use it to iterate over the keys of a Map.
For example,
map
with initial key-value pairs.keys()
method to get an iterator object iterator
for the map
.for...of
loop to iterate over the iterator
and log each key to the console using console.log()
.const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.keys();
for (const key of iterator) {
console.log(key);
}
a b c
In JavaScript, we can use the keys()
method to convert a Map object to an array of keys.
For example,
map
with initial key-value pairs.keys()
method to get an iterator object iterator
for the map
.iterator
to an array using the Array.from()
method and store it in the variable arrayOfKeys
.arrayOfKeys
to the console using console.log()
.const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.keys();
const arrayOfKeys = Array.from(iterator);
console.log(arrayOfKeys);
[ 'a', 'b', 'c' ]
In JavaScript, we can use the keys()
method to iterate over a Map object containing objects as keys.
For example,
map
with initial key-value pairs where keys are objects.keys()
method to get an iterator object iterator
for the map
.for...of
loop to iterate over the iterator
and log each key to the console using console.log()
.const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
[key1, 'value1'],
[key2, 'value2']
]);
const iterator = map.keys();
for (const key of iterator) {
console.log(key);
}
{ id: 1 } { id: 2 }
In this JavaScript tutorial, we learned about keys() method of Map: the syntax and few working examples with output and detailed explanation for each example.