How to check if object exists in array objects in JavaScript


To check if an array of objects includes a particular object in JavaScript, you can use the find method along with the === operator. Here is an example code snippet:

const array = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

const objectToFind = { id: 2, name: 'Jane' };

const objectFound = array.find(obj => obj === objectToFind);

if (objectFound) {
  console.log('Object found:', objectFound);
} else {
  console.log('Object not found');
}

In the above example, we have an array of objects named array. We want to check if this array includes an object named objectToFind. To do this, we use the find method which returns the first element in the array that satisfies the provided testing function. We pass a lambda function that checks if each object in the array is equal to the objectToFind using the === operator. If the object is found, it is stored in the objectFound variable and printed to the console. If not, a message is printed indicating that the object was not found.

Using ES6

const arr = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" }
];

const obj = { id: 2, name: "Jane" };

const includesObj = arr.some(item => JSON.stringify(item) === JSON.stringify(obj));

console.log(includesObj); // Output: true

In this example, we have an array of objects arr and an object obj. We want to check if the array includes the object or not.

We can use the some() method to iterate through the array and check if any of the objects in the array matches the given object.

Inside the some() method, we compare the current object in the array with the given object using JSON.stringify() to compare the object’s values.

If any of the objects in the array match the given object, the some() method will return true. Otherwise, it will return false. In this example, the output is true since the array includes the object { id: 2, name: "Jane" }.