How to Find an Object in a JavaScript Array?

Estimated read time 1 min read

You can use the Array.prototype.find() method to find an object in a JavaScript array.

Here’s an example that demonstrates how to find an object in an array based on a specific property:

const people = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Jim", age: 35 },
  { name: "Jack", age: 40 },
  { name: "Jill", age: 20 }
];

const person = people.find(person => person.name === "Jim");

console.log(person);
/*
Output:
{ name: "Jim", age: 35 }
*/

In this example, the find() method is used to find the first object in the people array that matches the condition person.name === "Jim". The find() method takes a callback function as its argument, and the callback function is called for each element in the people array until a truthy value is returned. If an object is found that matches the condition, the find() method returns it and stops searching. If no object is found, the find() method returns undefined.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply