Categories
JavaScript Answers

How to search for an object in an array of objects with JavaScript?

Spread the love

To search for an object in an array of objects with JavaScript, we use the array some method.

For instance, we write

const listOfObjecs = [
  { id: 1, name: "Name 1", score: 11 },
  { id: 2, name: "Name 2", score: 22 },
  { id: 3, name: "Name 3", score: 33 },
  { id: 4, name: "Name 4", score: 44 },
  { id: 5, name: "Name 5", score: 55 },
];

const object = { id: 3, name: "Name 3", score: 33 };
const booleanValue = listOfObjecs.some(
  (item) =>
    item.id === object.id &&
    item.name === object.name &&
    item.score === object.score
);

to call listOfObjects.some with a callback that checks if the id property of each item in listOfObjects equals object.id.

And we do the same with the name and score properties and combine the expressions with logical and.

Since the object that meets this condition exists in listOfObjects, true is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *