To retrieve the first element of a Map
object, there are multiple approaches you can take.
- Using the
entries()
method andnext()
:
const map = new Map([
['name', 'Alex Hales'],
['age', 27],
['country', 'United States']
])
const first = map.entries().next().value
console.log(first)
// ['name', 'Alex Hales']
The entries()
method returns an iterator object with key-value pairs. By calling next()
once, you can retrieve the first element from the iterator.
- Converting to an array and accessing the first element:
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']
By using Array.from(map)
or the spread operator (...map
), you can convert the Map
object into an array. Then, accessing the element at index 0
will give you the first key-value pair.
- Using array destructuring with
keys()
orvalues()
:
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'
You can utilize array destructuring to extract the first key or value by calling keys()
or values()
on the Map
object.
To learn more about the Map
object and working with key-value pairs in JavaScript, you can refer to this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.