Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search an array for matching attribute

Tags:

javascript

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" }}   ]; 
like image 881
Chap Avatar asked Jan 30 '10 03:01

Chap


People also ask

How do you find a matching element in an array?

To find the first array element that matches a condition:Use the Array. find() method to iterate over the array. Check if each value matches the condition. The find method returns the first array element that satisfies the condition.

How do you search an array of objects?

If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)

How do you check if a property exists in an array of objects JavaScript?

JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .


2 Answers

for(var i = 0; i < restaurants.length; i++) {   if(restaurants[i].restaurant.food == 'chicken')   {     return restaurants[i].restaurant.name;   } } 
like image 194
Matthew Flaschen Avatar answered Oct 01 '22 19:10

Matthew Flaschen


you can also use the Array.find feature of es6. the doc is here

return restaurants.find(item => {    return item.restaurant.food == 'chicken' }) 
like image 41
chenkehxx Avatar answered Oct 01 '22 19:10

chenkehxx