To get the first element of a Map
object, you can use the entries()
method to obtain an iterator object containing the map's keys and values. After that, call the next()
method on the iterable to retrieve the first element of the Map
:
const map = new Map([
['name', 'Alex Hales'],
['age', 27],
['country', 'United States']
])
const first = map.entries().next()
console.log(first.value)
// [ 'name', 'Alex Hales' ]
The entries()
method returns an iterator object containing the [key, value]
pairs for all elements in the Map
object in insertion order. The next()
method returns the next element in the iterable object.
Since we call the next()
method only once on the iterable, it returns the first element in the sequence.
An alternate approach is to use the Array.from()
method or spread operator (...
) to convert the Map
object into an array and then access the first element at index 0
:
const map = new Map([
['name', 'Alex Hales'],
['age', 27],
['country', 'United States']
])
const first = Array.from(map)[0] // OR [...map][0]
console.log(first)
// [ 'name', 'Alex Hales' ]
Finally, you can also use the array destructuring with the keys()
and values()
method to obtain the first key and value in the Map
object:
const map = new Map([
['name', 'Alex Hales'],
['age', 27],
['country', 'United States']
])
const [firstKey] = map.keys()
console.log(firstKey) // name
const [firstVal] = map.values()
console.log(firstVal) // Alex Hales
Read this article to learn more about the Map
object and how to create collections of key-value pairs in JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.