简体   繁体   中英

AngularJS filter nested array and return parent object

I've recently started fiddling around with 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.

$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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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