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" }} ];
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.
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.)
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 .
for(var i = 0; i < restaurants.length; i++) { if(restaurants[i].restaurant.food == 'chicken') { return restaurants[i].restaurant.name; } }
you can also use the Array.find
feature of es6
. the doc is here
return restaurants.find(item => { return item.restaurant.food == 'chicken' })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With