Search an array for matching attribute
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", "开发者_如何学Gofood" : "pizza" }}
];
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'
})
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;
for (x in restaurants) {
if (restaurants[x].restaurant.food == 'chicken') {
return restaurants[x].restaurant.name;
}
}
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
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;
}
}
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;
}
@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
精彩评论