Sometimes, we want to search an array for matching attribute with JavaScript.
In this article, we’ll look at how to search an array for matching attribute with JavaScript.
How to search an array for matching attribute with JavaScript?
To search an array for matching attribute with JavaScript, we use the array find
method.
For instance, we write
const restaurants = [
{ restaurant: { name: "McDonald's", food: "burger" } },
{ restaurant: { name: "KFC", food: "chicken" } },
{ restaurant: { name: "Pizza Hut", food: "pizza" } },
];
const chickenRestaurant = restaurants.find((item) => {
return item.restaurant.food === "chicken";
});
to call restaurants.find
with a callback that returns the first object in restaurants
that has the restaurant.food
property equal to 'chicken'
.
Conclusion
To search an array for matching attribute with JavaScript, we use the array find
method.