Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by Holly Mandarich
To get the first element of a Map
, use destructuring assignment, e.g.
const [firstKey] = map.keys()
and const [firstValue] = map.values()
. The
keys()
and values()
methods return an iterator object that contains the
Map's keys and values.
const map = new Map(); map.set('a', 1); map.set('b', 2); const [firstKey] = map.keys(); console.log(firstKey); // 👉️ a const [firstValue] = map.values(); console.log(firstValue); // 👉️ 1
In the code snippet we called the keys()
method on the map to get an iterator
that contains the keys of each element in the map.
We then use destructuring assignment to get the first key and assign it to a variable.
To get the value of the first element, we repeat the same process, but call the
values()
method instead.
Another way to get the first element of a map is to convert the map into an
array and access the element at index 0
.
const map = new Map(); map.set('a', 1); map.set('b', 2); const first = [...map][0]; console.log(first); // 👉️ ['a', 1]
In the code snippet we use the
spread syntax
to convert the map into an array and access the element at index 0
.
This returns an array containing the key and value of the first element in the map.
We can also get the first element of a Map by using some of the methods on the map instance.
const map = new Map(); map.set('a', 1); map.set('b', 2); const iterator = map.entries(); const firstIteration = iterator.next(); // {value: ['a', 1], done: false} const first = firstIteration.value; console.log(first); // 👉️ ['a', 1]
In the code snippet, we first get an iterator containing the elements of the map.
We then an object containing the value of the first iteration.
Finally, we access the value
property on the object to get an array of the key
and value of the first element in the map.