简体   繁体   English

AngularJS过滤嵌套数组并返回父对象

[英]AngularJS filter nested array and return parent object

I've recently started fiddling around with AngularJS. 我最近开始摆弄AngularJS。 I'm making checkbox filters for my wine store. 我正在为我的葡萄酒商店制作复选框过滤器。 An item looks like this: 一个项目看起来像这样:

        {
     "id": 17,
     "name": "Ermelinda Freitas Reserva",
     "tag_ids": [40, 12, 56, 6, 60],
     "tag_names": ["Roasted", "Robust", "Blackberry", "Mouth-filling", "Animal"],
     "price": 29,
     "weight": "0",
     "image": "1467208469_wijn1.jpg",
     "stock": 57,
     "year": 1998,
     "special": 0,
     "color_id": 1,
     "color": "Red",
     "region_id": 25,
     "region": "Alentejo",
     "country_id": 6,
     "country": "Portugal",
     "grape_ids": [34, 35, 20],
     "grape_names": ["Castelão", "Touriga Naçional", "Cabernet Sauvignon"]
 }

I've manage to make filters for countries and other non-array properties of the item like this: 我设法为该项目的国家/地区和其他非数组属性创建了过滤器,如下所示:

for(i = 0; i< wines.length; i++){

      if($scope.countries.indexOf(wines[i].country) === -1) $scope.countries.push(wines[i].country);
    };

But now i'm trying to make one for the grapes. 但是现在我正在为葡萄做一个。 I started off by collecting all unique values in an array as such: 我首先收集了数组中的所有唯一值,如下所示:

angular.forEach($scope.wines, function(wine){
  angular.forEach(wine.grape_names, function(grape){
    for(i = 0; i< wine.grape_names.length; i++){
      if($scope.grapes.indexOf(wine.grape_names[i]) === -1) $scope.grapes.push(wine.grape_names[i]);
    };
  });
})

So now I need to check if an item has any grapes that match the selected filter and here is where I am stuck: 因此,现在我需要检查某个项目是否有与所选过滤器匹配的葡萄,这就是我遇到的问题:

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){

  angular.forEach(wine.grape_names, function(grape){

    return $scope.filter.grape[grape] || noFilter($scope.filter.grape);
  })
};

The filters : 过滤器:

<div class="col-lg-3 col-md-4 col-sm-6 " data-id="{{wine.id}}" ng-init="getQuantity(wine.id)" data-ng-repeat="wine in filteredWines =(wines | orderBy:defaultOrder | filter:filterByColor | filter:filterByCountry | filter:filterByGrape | priceRangeFilter:priceRangeSlider | yearRangeFilter:yearRangeSlider | filter:search) | start: (currentPage - 1) * itemsPerPage | limitTo:itemsPerPage">

在此处输入图片说明

All help is very welcome ! 所有帮助都非常欢迎!

Problem is you are only checking the first iteration of the forEach for grape_names, you return from the function there. 问题是您只在forEach的第一次迭代中检查grape_names,然后从那里的函数返回。

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){
  var found = noFilter($scope.filter.grape);
  angular.forEach(wine.grape_names, function(grape){
     found = $scope.filter.grape[grape] || found;
  })
  return found;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM