prozaek.prozaek prozaek.prozaek - 1 month ago 6
AngularJS Question

How make filter for search in object?

Please help fix the script.

I have follow data structure in $scope.peoples

I need find follow object: '{name: 'dima', age: '4'}' and put it in $scope.filteredPeoples. I need use filter.

My filter version:

app.controller('mainController', ['$scope', 'namesFilter', function($scope, namesFilter) {
$scope.peoples = [
{name: 'anton', age: '1'},
{name: 'serg', age: '2'},
{name: 'sveta', age: '3'},
{name: 'dima', age: '4'},
{name: 'stas', age: '5'},
{name: 'pavel', age: '6'}
];
$scope.filteredPeoples = namesFilter($scope.peoples, {name: 'dima'});
}]).filter('names',function() {
return function(array) {
var result = [];

array.forEach(function(item, i, arr) {
if(item.color == 'dima') {
result.push(item);
};
});

return result;
};
});


But it filter does not worked. Console is not displays error messages, but filteredPeoples is empty array.

JSFIDDLE

Answer

You need to check on the proper object property :

if(item.name== 'dima') { //not item.color
            result.push(item);
          };

Here's your updated working fiddle