Search an array for matching attribute

Viewed 188051

I have an array, I need to return a restaurant's name, but I only know the value of its "food" attribute (not it's index number).

For example, how could I return "KFC" if I only knew "chicken"?

restaurants = 
  [
    {"restaurant" : { "name" : "McDonald's", "food" : "burger" }},
    {"restaurant" : { "name" : "KFC",        "food" : "chicken" }},
    {"restaurant" : { "name" : "Pizza Hut",  "food" : "pizza" }}
  ];
8 Answers
for(var i = 0; i < restaurants.length; i++)
{
  if(restaurants[i].restaurant.food == 'chicken')
  {
    return restaurants[i].restaurant.name;
  }
}
for (x in restaurants) {
    if (restaurants[x].restaurant.food == 'chicken') {
        return restaurants[x].restaurant.name;
    }
}
let restaurant = restaurants.find(element => element.restaurant.food == "chicken");

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

as you can see in MDN Web Docs

Related