Categories
JavaScript Answers

How to get the first item from a map with JavaScript?

Spread the love

Sometimes, we want to get the first item from a map with JavaScript.

In this article, we’ll look at how to get the first item from a map with JavaScript.

How to get the first item from a map with JavaScript?

To get the first item from a map with JavaScript, we can use the next method.

For instance, we write

const m = new Map();
m.set("key1", {});
m.set("keyN", {});

console.log(m.entries().next().value);

to create the map m.

Then we get an iterator with the key and value with entries.

And we call next to get the first entry.

We get its key value pair from the value property.

Also, we can get an iterator with the keys with keys.

console.log(m.keys().next().value);

And, we can get an iterator with the values with values.

console.log(m.values().next().value);

Conclusion

To get the first item from a map with JavaScript, we can use the next method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *