How to Find an Object in a List Using JavaScript?

Estimated read time 1 min read

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

Here’s an example that demonstrates how to find an object in a list 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 list (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 list 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