views:

387

answers:

2

I have a JSON 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" }}
  ];
+3  A: 
for(var i = 0; i < restaurants.length; i++)
{
  if(restaurants[i].restaurant.food == 'chicken')
  {
    return restaurants[i].restaurant.name;
  }
}
Matthew Flaschen
A: 

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; } }

laVie