Check if a Map has an Object Key using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 26, 2022

banner

Photo from Unsplash

Check if a Map has an Object Key #

To check if a Map has an object key, call the has() method, passing it a reference to the object, e.g. map.has(obj). 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 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

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
// 👇️️ false console.log({country: 'Chile'} === {country: 'Chile'}); // 👇️️ true console.log(obj === obj);

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

The for...of loop iterates over iterable objects like arrays, strings, and Maps.

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 the existence of the object key, we use the break keyword to exit the loop and avoid unnecessary work.

Further Reading #

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.