Reputation: 3553
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" }}
];
Upvotes: 87
Views: 209621
Reputation: 1625
you can also use the Array.find
feature of es6
. the doc is here
return restaurants.find(item => {
return item.restaurant.food == 'chicken'
})
Upvotes: 83
Reputation: 4437
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
Upvotes: 9
Reputation: 57209
for (x in restaurants) {
if (restaurants[x].restaurant.food == 'chicken') {
return restaurants[x].restaurant.name;
}
}
Upvotes: 9
Reputation: 1122
@Chap - you can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = [
{ "restaurant": { "name": "McDonald's", "food": "burger" } },
{ "restaurant": { "name": "KFC", "food": "chicken" } },
{ "restaurant": { "name": "Pizza Hut", "food": "pizza" } }
].
res = JSON.search( data, '//*[food="pizza"]' );
console.log( res[0].name );
// Pizza Hut
DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
http://www.defiantjs.com/#xpath_evaluator
Upvotes: 1
Reputation: 1700
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;
Upvotes: 53
Reputation: 9848
you can use ES5 some. Its pretty first by using callback
function findRestaurent(foodType) {
var restaurant;
restaurants.some(function (r) {
if (r.food === id) {
restaurant = r;
return true;
}
});
return restaurant;
}
Upvotes: 1
Reputation: 69
Must be too late now, but the right version would be:
for(var i = 0; i < restaurants.restaurant.length; i++)
{
if(restaurants.restaurant[i].food == 'chicken')
{
return restaurants.restaurant[i].name;
}
}
Upvotes: 3
Reputation: 284786
for(var i = 0; i < restaurants.length; i++)
{
if(restaurants[i].restaurant.food == 'chicken')
{
return restaurants[i].restaurant.name;
}
}
Upvotes: 82