如何使用过滤器过滤对象数组中的数组?

时间:2018-11-22 13:56:58

标签: javascript angularjs

我有一系列使用“过滤器”的产品和模型

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.products = [{
      'id': 1,
      'category': 'Tv',
      'models': [{
          'modelno': 12,
          'modelname': 'ASF456'

        },
        {
          'modelno': 13,
          'modelname': 'Aip456'

        }
      ]
    },

    {
      'id': 2,
      'category': 'Mobile',
      'models': [{
          'modelno': 21,
          'modelname': 'FGH74'

        },
        {
          'modelno': 22,
          'modelname': 'UIO06'

        }
      ]

    }

  ];

  $scope.search = '';
  $scope.filterData = function() {
    return $scope.products.filter(function(item) {

      return (item.id.toString().indexOf($scope.search) > -1

        ||
        (item.category.toLowerCase().indexOf($scope.search)) > -1)



    });

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="search">
  <h1 ng-repeat="x in filterData() | filter :search">{{x.id}} {{x.category}}</h1>
</body>

按ID和类别过滤这些产品。 过滤器正在工作,但我想在过滤器模型名称内添加一个字段。

如何将过滤器设置为仅应用于数组的id,category和modelname字段,而不是应用于每个字段?

如何将过滤器设置为仅应用于数组的id,category和modelname字段,而不是应用于每个字段?

我想按ID类别,型号名

进行过滤

现在这两个字段id都已完成,类别过滤已完成,但是我也想添加模型名称,但是模型名称位于模型数组中,因此我面临问题

2 个答案:

答案 0 :(得分:1)

您可以添加另一个或类似的条件

 || (item.models !== null && item.models.length > 0 && item.models.filter(e => {return e.modelname.search($scope.search) > 0 }).length > -1)

答案 1 :(得分:0)

我是否正确理解-您想通过$scope.products来过滤id?如果是这样,请尝试这样:

<input ng-model="id " type="number" min="0"/>
<br />
<div ng-repeat="x in products | IDFiletr:id">
  {{x.category}}
  <br />
</div>

JS:

app.filter('IDFiletr',function(){
    return function(data, id) {
        if (!id) return data;
        var ids = [];
        angular.forEach(data, function(item){
            if(item.id === id) {
                ids.push(item);
            }
        });
        return ids;
    };
});

朋克:http://plnkr.co/edit/q9DsvZP4scA1oKsJj3Vu?p=preview