返回由键/值对定义的数组

return array defined by a key/value pair

本文关键字:定义 数组 返回      更新时间:2023-09-26

如何根据数组中的键/值对筛选return结果。

假设我有这个数组:

 .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 
 ];

我有下面的JavaScript,它要么向用户返回经过dishtype过滤的结果,要么返回整个列表。我想更改返回整个列表,只返回具有type: 'top_10'值的项目列表

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

我试着写一个合适的语法来修改return:dishes,但在JS中,无法正常工作。。。谢谢你的帮助!

HTML编辑(解决方案)对于任何来到这里的人来说,这是我找到的解决方案:

   .filter('selectedDishType', function() {
return function(dishes, dishTypes) { // returns ad hoc categories selected by user
    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){ // returns only "type =='top_10' to avoid long loading time
            return dish.type;
        });
      }
    };
})

将过滤功能更改为

return dishes.filter(function(dish){
  return dish.type.toLowerCase().indexOf(dishTypes) != -1;
});

我认为这段代码可以在上运行

您可以使用下划线并执行类似操作:

var the_top_10 = _.filter(dishes, function(dish){ return dish.type=='top_10'; });

一般来说,你可以使用下划线(http://underscorejs.org/#where)

"where_.where(列表,属性)浏览列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。"