Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  80] [ 7]  / answers: 1 / hits: 37415  / 9 Years ago, sun, may 31, 2015, 12:00:00

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.


More From » arrays

 Answers
7

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>




[#66396] Thursday, May 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leonardok

Total Points: 114
Total Questions: 94
Total Answers: 103

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;