Check if a Map has an Object Key using JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

banner

Photo by Ashley Batz

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 pass 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

Objects are compared by reference in JavaScript and not by their contents.

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

In the scenario that you don't have a reference to the object, you can 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 key is an object and contains a property country that is equal to Chile.

In this example, we don't make use of the value variable, however I've included it just in case your use case needs 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee