在过滤器中使用angular.forEach

时间:2016-12-09 10:34:38

标签: angularjs

我有一个带有一些id的数组(1)和另一个带有生物的数组(2),它们有id(就像在第一个数组中)和名字。我想创建新数组(它看起来像(1)id数组,但只有(2)中的id)。所以我认为我需要使用过滤器 (1)

$scope.main = ['dog', 'cat', 'bird', 'bug', 'human'];

(2)

  $scope.creatures = [
    {
      id: 'cat',
      name : 'fluffy'
    },
    {
      id: 'cat',
      name : 'mr.Kitty'
    },
    {
      id: 'human',
      name: 'Rachel'
    },
    {
      id: 'cat',
      name : 'Lucky'
    },
    {
     id: 'cat',
     name: 'Tom'
    }
    ];

过滤器:

  $scope.results = $scope.main.filter(function(item) {
    angular.forEach($scope.creatures, function(creature) {
      return item === creature.id;
    });
  });  

我希望它会

$scope.results === ['cat', 'human'];

但我有

$scope.results // [0] empty array

我哪里错了? Plnkr example

2 个答案:

答案 0 :(得分:3)

它不起作用,因为你在forEach循环中的第一次迭代中返回。您可以按如下所示使其正常工作:

Updated Plunker

$scope.results = [];
$scope.main.filter(function(item) {
   angular.forEach($scope.creatures, function(creature) {
      if(item === creature.id){
       if( $scope.results.indexOf(item) === -1){
         $scope.results.push(item);
        }
      }
   });
});

我们不再在过滤器内再次循环,而是先从生物数组中取出ID,然后在主数组中过滤它们,如下所示:

 $scope.results = [];
 $scope.ids = $scope.creatures.map(function (creature){
   return creature.id;
 });


 $scope.ids.map(function (id){
   if($scope.main.indexOf(id) !== -1){
     if( $scope.results.indexOf(id) === -1){
       $scope.results.push(id);
     }
   }
 });
console.log($scope.results);

答案 1 :(得分:0)

你的羽毛球做了一些改动,它现在正在运作。你能查看这段代码吗?

var app = angular.module('App', []);

app.controller('Ctrl', function($scope, $timeout){
  $scope.main = ['dog', 'cat', 'bird', 'bug', 'human'];

  $scope.creatures = [
    {
      id: 'cat',
      name : 'fluffy'
    },
    {
      id: 'cat',
      name : 'mr.Kitty'
    },
    {
      id: 'human',
      name: 'Rachel'
    },
    {
      id: 'cat',
      name : 'Lucky'
    },
    {
     id: 'cat',
     name: 'Tom'
    }
    ];
    var array = [];
    $scope.call = function() {
    angular.forEach($scope.main,function(item){

    angular.forEach($scope.creatures, function(creature) {

      if(item == creature.id){
        // console.log('item',item,' creatureId',creature.id);
        if(array.indexOf(item) < 0 ){
          array.push(item);
        }

        console.log(array);
      }
    });
    $scope.results = array;
    });
  };

  $scope.call();
 console.log('result ',$scope.results);

});
相关问题