In this article we will learn how to get first element of map.
It is very common to get first element of map in JavaScript.
Problem
Now we have a problem, which is that we want to get the first element from the map.
Now let's define a map like this:
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
console.log(map);
// Map(2) { 'name' => 'John', 'age' => 30 }
And we only want the first element of the map, so the output becomes like this:
[ 'name', 'John' ]
How to solve this problem?
There is more than one solution to this problem, such as:
- Using
entries().next()
methods Array.from()
method
Now we will explain these solutions in detail.
Get first element using entries()
method
We can use entries()
method to solve this problem.
but first we should know what entries()
method do?
The entries()
method returns a new iterator object that contains the [key, value] pairs for each element in the Map object in insertion order. (Source: MDN)
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
console.log(map.entries());
Output
[Map Entries] { [ 'name', 'John' ], [ 'age', 30 ] }
Now it is easy to get the first element using next()
method.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
console.log(map.entries().next());
Output
[ 'name', 'John' ]
Since we call the next()
method only once on the iterable, it returns the first element in the sequence.
Get first element using Array.from
method
We can use Array.from
to solve this problem as well.
Array.from
will convert the map into an array, and then we can easily get the first element.
// Map
const map = new Map([
['name', 'John'],
['age', 30],
]);
// Convert to array
const toArray = Array.from(map);
// Print the result:
console.log(toArray[0]);
Output
[ 'name', 'John' ]
Thank you for reading
Thank you for reading my blog. 🚀