I am dealing with a json array and performing search on it. The code seems to be ok but not giving the output. This is my code
var restaurants = [
{"restaurant" : { "name" : "McDonald's", "food" : "burger", "drink" : "coke", "content" : "Lorem ipsum dolor sit amet" }},
{"restaurant" : { "name" : "KFC", "food" : "chicken", "drink" : "pepsi", "content" : "Lorem ipsum dolor sit amet" }},
{"restaurant" : { "name" : "Pizza Hut", "food" : "pizza", "drink" : "sprite", "content" : "Lorem ipsum dolor sit amet" }},
{"restaurant" : { "name" : "Dominos", "food" : "pizza", "drink" : "root beer", "content" : "Lorem ipsum dolor sit amet" }},
{"restaurant" : { "name" : "Popeyes", "food" : "chicken", "drink" : "mist", "content" : "Lorem ipsum dolor sit amet" }}
];
And my method for search is
function filter( restaurants, food, drink) {
var result = [];
for( var i= 0, len = restaurants.length; i < len; i++) {
var el = restaurants.restaurant[i];
if( el.food === food && el.drink === drink ) {
result.push( el );
}
}
return result;
}
But in console it is showing Uncaught TypeError: Cannot read property 'length' of undefined. What is wrong with the function? How can i perform a complete search? Is it about string length function?
filterfunction being called? My guess is that yourrestaurantsparameter is overriding the globalrestaurantsthat contains the actual data.restaurantsvariable infilter()function or it throws an error.foodanddrink, yet, you're only defining single<input>element to enter data to search for. However, the main problem is that you're not passing the arguments to thefilterfunction you declared.