This post will discuss how to obtain the key that matches a value in a map in JavaScript.

To obtain the key that matches a value in a map in JavaScript, we can use one of the following functions:

1. Using Array.find() function

A simple solution is to use the Object.entries() function to get an array of the key-value pairs, and find a pair that matching the given value using the Array.find() function. Then we can extract only the key from the pair using the index notation. Here’s an example of how we can achieve this:

Download  Run Code

 
Note that this approach creates an intermediate array and will work only with object literal as the map. To achieve the same with a Map object instead, we can use the Array.from() function. It returns an array of the key-value pairs, upon which Array.find() function can be called.

Download  Run Code

2. Using Array.filter() function

The Array.find() function only returns the first key that matches a predicate. To get all matching keys, consider using the Array.filter() function instead. The following code illustrates this:

Download  Run Code

 
To achieve the same with a Map instead, we can use the Array.from() function. It returns an array of the key-value pairs, upon which Array.filter() function can be called. Here’s an example:

Download  Run Code

3. Using Map.forEach() function

Another alternative is to use the Map.forEach() function to iterate over the Map object, and construct an array containing all keys matching the specified value. The following code illustrates this:

Download  Run Code

 
The above solution will iterate over the map’s entries only once and avoid creating any intermediate arrays. Another option is to iterate over the key-value pairs of the map using a for…of loop and use array destructuring assignment to get the key and value of each pair. Then, we can compare the value to the given target, and return or store the keys. The following code illustrates this:

Download  Run Code

That’s all about obtaining the key that matches a value in a map in JavaScript.