How To Get A Value Of A Map By Its Key In JavaScript

We will learn about how to get a value of a map by its key in JavaScript with two methods. Each approach is relatively straightforward, and you can choose whatever you want.

How to get a value of a map by its key in JavaScript

Using get()

To get the value of a map element by its key in JavaScript, you can use this method by passing its key to the parameter.

Syntax:

get(key)

Parameter:

• key: the map’s key you want to get.

You just call get() method on this Map and pass the key as an argument to the function. This method will return the corresponding map element’s value for that key. If there is no map element with that key, then undefined is returned.

For example:

var map = new Map();
map.set("learn","LEARN")
map.set("share","SHARE")
map.set("it","IT")

// Get a map element with key “learn”
console.log(map.get("learn"))

Output:

LEARN

The below example created a new map to test the solution. This map contains 3 elements with the keys “learn”, “share” and “it” respectively. Then, we get a value of a map which has the key “learn” using the .get() method on the map variable. The returned result indicates the value of the map and is exactly what we are expecting for.

Using a for loop

This approach does not introduce any new methods. Instead it is an improved version of the first one because it can work on a list of keys which you want to find the map element. First, we declare our keys in an array and then use a for loop to iterate through these values and get the map element with .get():

var map = new Map();
map.set("learn","LEARN")
map.set("share","SHARE")
map.set("it","IT")

// Create an array of keys
var array = ["share","it","for","learn"]

// Iterate over the array
for (i of array)
console.log(map.get(i))

Output:

SHARE
IT
undefined
LEARN


As you can see, this example declares the keys we want to find its corresponding map’s value are “share”, “it”, “for” and “learn” respectively. However, because there is no element with the key “for” in our map, therefore the value “undefined” has been returned and printed out. If you don’t want to print out any undefined value, you can guard it with an if statement, for example:

var map = new Map();
map.set("learn","LEARN")
map.set("share","SHARE")
map.set("it","IT")

// Create an array of keys
var array = ["share","it","for","learn"]

// Iterate over the array
for (i of array)
if (map.get(i)) console.log(map.get(i))

Output:

SHARE
IT
LEARN

Summary

We have shown you instructions on how to get a value of a map by its key in JavaScript using two different approaches. It would help if you considered that the first method is what most programmers use. Moreover, if you want to work more with maps, you can take a look at this tutorial: How To Iterate Over A Map In Reverse Order Using JavaScript.

Maybe you are interested: