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
In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.
Shims can be found here: MDN Array.filter or ES5-shim
var result = restaurants.filter(function (chain) {
return chain.restaurant.food === "chicken";
})[0].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'
})