mssuley
mssuley

Reputation: 58

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

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_id matches those in item_ids array.

Upvotes: 0

Views: 37372

Answers (1)

jad-panda
jad-panda

Reputation: 2547

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

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>

Upvotes: 1

Related Questions