Check If A Set Contains An Object In JavaScript

In this article, we will cover how to check if a Set contains an object in JavaScript. To achieve this, we need to use the `has()` method on our `Set` and pass the object as an argument. The `has()` method returns `true` if the object exists inside the `Set` or `false` if the object does not exist.

First, let’s start by creating two objects and initializing them with values –

const obj = {

  key: "value"

};

const anotherObj = {

  key: "value"

};

Then, let’s create a `Set` using the `Set()` constructor and assign our first object `obj` to it.

const set = new Set([obj]);

Now, to check if our object exists inside the set, we will call the `has()` method on the `set`, passing in our object as an argument, and then we will print the output on the console.

console.log(set.has(obj));
true is returned as set contains the object

As we can see, we got `true` on the console as our object `obj` exists in `set`. Let’s do the same check for the second object `anotherObject` and see what we get on the console.

console.log(set.has(anotherObj));
false is returned as the set doesn't contain the object

Since, `anotherObject` does not exist in `set`, the `has()` method returned `false` as a result.

Finally, we can wrap this logic inside of a function so that we can pass any object and set we need, and check if the object exists inside the set –

const isObjectInSet = (set, object) => {

return set.has(object);

};

Now, let’s call our function passing in `set` and `obj` as arguments and print the result on the console –

console.log(isObjectInSet(set, obj));
function returns true since set contains object

Leave a Reply