Borislav Hadzhiev
Fri Oct 29 2021·1 min read
Photo by Priscilla Du Preez
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.
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'}