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));
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));
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));