How to get a Value of a Map by its Key using JavaScript


Borislav Hadzhiev

Fri Oct 29 20211 min read

Get a Value of a Map by a Key #

To get a value of a Map by a key, call the get() method, passing it the name of the key as a parameter, e.g. map.get('myKey'). The get method returns the value associated to the provided key.

const map1 = new Map([ ['country', 'Chile'], ['city', 'Santiago'], ]); console.log(map1.get('country')); // ๐Ÿ‘‰๏ธ "Chile"

We used the Map.get method to get a value of a Map by a key.

The only parameter the method takes is the name of the key.

The method returns the value that's associated with the specified key, or undefined if the key doesn't exist in the `Map` object.
const map1 = new Map([ ['country', 'Chile'], ['city', 'Santiago'], ]); console.log(map1.get('test')); // ๐Ÿ‘‰๏ธ undefined

If the keys in your Map are arrays or objects, you have to pass them to the get() method by reference.

const obj = {country: 'Chile'}; const map1 = new Map([[obj, {city: 'Santiago'}]]); console.log(map1.get(obj)); // ๐Ÿ‘‰๏ธ {city: 'Santiago'}

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee