Check if a Key or Value exists in a Map in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
6 min

banner

# Table of Contents

  1. Check if a Key exists in a Map in JavaScript
  2. Check if a Value exists in a Map in JavaScript
  3. Check if a Map has an Object Key in JavaScript

# Check if a Key exists in a Map in JavaScript

Use the Map.has() method to check if a key exists in a Map object.

The has() method returns true if the specified key exists in the Map, otherwise, it returns false.

index.js
const map = new Map(); map.set('name', 'bobbyhadz'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true console.log(map.has('age')); // ๐Ÿ‘‰๏ธ false if (map.has('name')) { // ๐Ÿ‘‡๏ธ this runs console.log('The `name` key exists in the Map object'); } else { console.log('The `name` key does NOT exist in the Map object'); }

check if key exists in map

The code for this article is available on GitHub

If you need to check if a value exists in a Map, click on the following subheading.

If you need to check if an object key exists in a Map, scroll down to the next subheading.

The only parameter the Map.has() method takes is the key of the element to test for presence in the Map.

The Map.has() method returns a boolean result:

  • true if the key exists in the Map object
  • false if the key doesn't exist in the Map object
The has() method returns true if the key is set to undefined, null or any other falsy value.
index.js
const map = new Map(); map.set('undef', undefined); map.set('null', null); map.set('nan', Number.NaN); console.log(map.has('undef')); // ๐Ÿ‘‰๏ธ true console.log(map.has('null')); // ๐Ÿ‘‰๏ธ true console.log(map.has('nan')); // ๐Ÿ‘‰๏ธ true

The method checks for existence, not whether the value is truthy or falsy.

If a value gets deleted from the map, the has method picks up the update immediately.

index.js
const map = new Map(); map.set('name', 'Tom'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true map.delete('name'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ false

We used the Map.delete() method to remove an element from the Map.

As expected, the call to the has() method returned false immediately after.

The same is the case when using the Map.set() method to add an element to the Map or the map.clear() method to remove all elements from the Map.

index.js
const map = new Map(); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ false map.set('name', 'bobbyhadz'); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ true map.clear(); console.log(map.has('name')); // ๐Ÿ‘‰๏ธ false

The Map.clear() method removes all elements from a Map object, so passing any key to the Map.has() method returns false after a call to Map.clear().

# Check if a Value exists in a Map in JavaScript

To check if a value exists in a Map:

  1. Use the values() method to get an iterator of the Map's values.
  2. Use the spread syntax (...) to convert the iterator to an array.
  3. Use the includes() method to check if the value is contained in the Map.
index.js
const map = new Map(); map.set('name', 'bobby'); // ๐Ÿ‘‡๏ธ ['bobby'] const values = [...map.values()]; console.log(values); console.log(values.includes('bobby')); // ๐Ÿ‘‰๏ธ true console.log(values.includes('alice')); // ๐Ÿ‘‰๏ธ false if (values.includes('bobby')) { // ๐Ÿ‘‡๏ธ this runs console.log('The value is contained in the Map'); } else { console.log('The value is NOT contained in the Map'); }

check if value exists in map

The code for this article is available on GitHub

We used the Map.values() method to get an iterator object that contains the Map's values.

index.js
const map = new Map(); map.set('name', 'bobby'); map.set('age', 30); // // ๐Ÿ‘‡๏ธ [ 'bobby', 30 ] const values = [...map.values()]; console.log(values);

We used the spread syntax (...) to unpack the values from the iterator into an array.

We could have also used the Array.from() method to convert the iterator to an array.

index.js
const map = new Map(); map.set('name', 'bobby'); // ๐Ÿ‘‡๏ธ ['bobby'] const values = Array.from(map.values()); console.log(values);

The last step is to use the Array.includes() method to check if the value is contained in the array.

Here's the same approach, abstracted in a reusable function.

index.js
function valueInMap(map, value) { const values = [...map.values()]; if (values.includes(value)) { console.log('โœ… value is contained in the Map'); return true; } console.log('โ›”๏ธ value is not contained in the Map'); return false; } const myMap = new Map(); myMap.set('name', 'bobby'); // ๐Ÿ‘‡๏ธ true console.log(valueInMap(myMap, 'bobby')); // ๐Ÿ‘‡๏ธ false console.log(valueInMap(myMap, 'alice'));

The valueInMap() function takes a Map object and a value as parameters and returns true if the value is contained in the Map and false otherwise.

Note that the Array.includes() method is case-sensitive.

index.js
const map = new Map(); map.set('name', 'bobby'); // ๐Ÿ‘‡๏ธ ['bobby'] const values = [...map.values()]; console.log(values); console.log(values.includes('bobby')); // ๐Ÿ‘‰๏ธ true console.log(values.includes('BOBBY')); // ๐Ÿ‘‰๏ธ false

If you need to check if a value is contained in a Map in a case-insensitive manner, use the Array.some() method.

index.js
const map = new Map(); map.set('name', 'bobby'); // ๐Ÿ‘‡๏ธ ['bobby'] const values = [...map.values()]; console.log(values); const str = 'BOBBY'; const valueInMap = values.some(value => { return value.toLowerCase() === str.toLowerCase(); }); console.log(valueInMap); // ๐Ÿ‘‰๏ธ true

We used the Array.some() method to iterate over the array of the Map's values.

The function we passed to the some() method gets called with each value in the array.

On each iteration, we use the String.toLowerCase() method to convert the string and the value to lowercase.

Converting both strings to lowercase allows us to perform a case-insensitive string comparison.

You can also use a for...of loop to check if a value exists in a Map.

# Check if a Value exists in a Map using a for...of loop

This is a three-step process:

  1. Use the values() method to get an iterator of the Map's values.
  2. Use a for...of loop to iterate over the iterator.
  3. Check if each value is equal to the supplied value.
index.js
const map = new Map(); map.set('name', 'bobby'); let valueInMap = false; for (const value of map.values()) { if (value === 'bobby') { valueInMap = true; // โœ… value: bobby console.log('value: ', value); break; } } console.log(valueInMap); // ๐Ÿ‘‰๏ธ true

check if value exists in map using for of

The code for this article is available on GitHub

We declared a new variable and initialized it to false.

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

On each iteration, we check if the current value is equal to a specific value.

If the condition is met, we set the boolean variable to true and break out of the loop.

The break statement is used to exit the loop prematurely once we find the matching value.

# Check if a Map has an Object Key in JavaScript

If you need to check if a Map has an object key, use the has() method.

The has() method will return true if the object key is contained in the Map and false otherwise.

index.js
const obj = {country: 'Chile'}; const map1 = new Map([[obj, {city: 'Santiago'}]]); // โœ… ( BEST ) - With reference console.log(map1.has(obj)); // ๐Ÿ‘‰๏ธ true console.log(map1.get(obj)); // ๐Ÿ‘‰๏ธ {city: 'Santiago'} // -------------------------------------------------------- // โœ… If you don't have a reference, loop over the map to check let hasKey = false; for (const [key, value] of map1) { if (typeof key === 'object' && key.country === 'Chile') { hasKey = true; break; } } console.log(hasKey); // ๐Ÿ‘‰๏ธ true

check if map has object key

The code for this article is available on GitHub

We used the Map.has() method to check if a Map has an object key.

Note that we passed the object by reference to the has() method.

This wouldn't work if you pass an object containing the same key-value pairs because it would be stored at a different location in memory.

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

JavaScript objects are compared by reference, and not by their contents.

index.js
const obj = {country: 'Chile'}; // ๐Ÿ‘‡๏ธ๏ธ false console.log({country: 'Chile'} === {country: 'Chile'}); // ๐Ÿ‘‡๏ธ๏ธ true console.log(obj === obj);

# Check if an Object key exists in a Map without a reference

If you don't have a reference to the object, use a for...of loop to iterate over the Map and check for the existence of the object key.

index.js
const map1 = new Map([[{country: 'Chile'}, {city: 'Santiago'}]]); let hasKey = false; for (const [key, value] of map1) { if (typeof key === 'object' && key.country === 'Chile') { hasKey = true; break; } } console.log(hasKey); // ๐Ÿ‘‰๏ธ true

check if object key exists in map without reference

The code for this article is available on GitHub

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

On each iteration, we check if the current key is an object and contains a country property that is equal to Chile.

You don't have to destructure the value variable if you don't need it.

After we have confirmed that the object key exists in the Map, we use the break statement to exit the loop and avoid unnecessary work.

We used the logical AND (&&) operator, so for the if block to run, both conditions have to be met.

The key has to be an object and it has to have a country property that is equal to Chile.

You can check for multiple properties and values to make your if statement more robust.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev