Javascript AngularJS:如何从对象数组中查找对象,给定数组中的属性值数组,使用 $filter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30558000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:23:25  来源:igfitidea点击:

AngularJS: how to find objects from an array of objects, given an array of property values in an array, using $filter

javascriptarraysangularjsangularjs-filter

提问by mssuley

Have a set of objects in an array (items array) that have property

在具有属性的数组(项目数组)中有一组对象

item_id:
[{item_id:1,...},{item_id:2,...}...]

Have another array with a set of

有另一个数组与一组

item_ids:
[2, 8, 10]

How do I use the $filter of angularjs to get array of objects from items array where item_idmatches those in item_idsarray.

如何使用 angularjs 的 $filter 从 items 数组中获取item_id与数组中匹配的对象item_ids数组。

回答by jad-panda

You can use custom filter to do this kind of filtration. and you can use use $filterservice if you want to do that in code instead of template.

您可以使用自定义过滤器来进行这种过滤。$filter如果您想在代码而不是模板中执行此操作,则可以使用使用服务。

Filter Guide

过滤指南

See the below code.

请参阅下面的代码。

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

app.controller('ctrl', function($scope, $filter) {

  $scope.items = [{
    item_id: 1
  }, {
    item_id: 2
  }, {
    item_id: 3
  }, {
    item_id: 4
  }];

  $scope.findList = [2, 4];
  $scope.findList2 = [3];

  // Using $filter service.
  $scope.usingservice = $filter('findobj')($scope.items, [1, 3])
});

app.filter('findobj', function() {

  return function(list, obj) {

    return list.filter(function(l) {
      if (obj.indexOf(l.item_id) >= 0) {
        return true;
      }
    });

  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <div ng-repeat="item in items | findobj: findList">
      {{item}}
    </div>
    <hr/>
    <div ng-repeat="item in items | findobj: findList2">
      {{item}}
    </div>
    <hr/>{{usingservice}}
  </div>
</div>