Looking to filter results based on a key/value pair in an array?
Consider this example array:
.factory('dishesFactory', function (){
var factory = {
dishes :[
{nameEnglish: 'TAPENADE',
nameLocal: 'Tapenade',
description: 'xxxxxx ',
region: 'Provence-Alpes-Côte d\'Azur',
regioncode: 'FR.B8',
itemid: 'FR002',
cuisineTypeIsoCode: 'FR',
dishCategory: 'Entrée / Appetizers',
country: 'France',
type: 'top_10'},
{nameEnglish: 'GREEK STYLE MUSHROOMS ',
nameLocal: 'Champignons à la grecque',
description: 'xxxxxxx',
region: 'All',
regioncode: '',
itemid: 'FR008',
cuisineTypeIsoCode: 'FR',
dishCategory: 'Entrée / Appetizers',
country: 'France',
type: ''}
// more entries
];
If you want to modify the JavaScript code so it only returns items with type: 'top_10'
, take a look at this snippet below:
.filter('selectedDishType', function() {
return function(dishes, dishTypes) {
console.log(dishTypes);
if (dishTypes.length > 0) {
return dishes.filter(function(dish) {
return dishTypes.indexOf(dish.dishCategory.toLowerCase()) != -1;
});
} else {
return dishes.filter(function(dish){
return dish.type === 'top_10';
});
}
};
})
Struggling with syntax changes? Check out the updated solution provided below for reference:
.filter('selectedDishType', function() {
return function(dishes, dishTypes) {
console.log(dishTypes);
if (dishTypes.length > 0) {
return dishes.filter(function(dish) {
return dishTypes.indexOf(dish.dishCategory.toLowerCase()) != -1;
});
} else {
return dishes.filter(function(dish){
return dish.type === 'top_10';
});
}
};
})