Conqueror Conqueror - 1 month ago 8
AngularJS Question

Angular filter a object by it's properties

I have an object with a series of object properties that is in the following similar structure (which is the way the data is coming back from a service):

{
"1": {
"type": "foo",
"name": "blah"
},
"2": {
"type": "bar"
},
"3": {
"type": "foo"
},
"4": {
"type": "baz"
},
"5": {
"type": "test"
}
}


When I do a ng-repeat, I can iterate over all 5 of these object, something like:

<div ng-repeat="item in items">{{item.type}}</div>


However, what I really want to do is iterate only over those items that are NOT the type "foo", namely 3 iterations instead of 5. I know that filters can somehow be leveraged to do this, but I am not sure how. I tried the following:

<div ng-repeat="item in items| !filter:{type:'foo'}">{{item.type}}</div>


but this doesn't work. In fact, even doing the following to limit to just 2 objects(those with item.type==="foo"), it doesn't work and does 5 iterations:

<div ng-repeat="item in items| filter:{type:'foo'}">{{item.type}}</div>


In essence, I want to do something similar to:

<div ng-repeat="item in items" ng-if="item.type !=='foo'>{{item.type}}</div>


However, I know that one doesn't work.

Answer

Filter works on arrays but you have an object literal.

So you can either convert your object literal into an array or create your own filter than takes in the object literal.

If you don't need those index values then converting to an array may be your best bet( Here's a fiddle with the array working: http://jsfiddle.net/NqA8d/3/):

$scope.items = [{
    "type": "foo",
        "name": "blah"
}, {
    "type": "bar"
}, {
    "type": "foo"
}, {
    "type": "baz"
}, {
    "type": "test"
}];

In case you'd like to do a filter, here's one way to do that:

myApp.filter('myFilter', function () {
    return function (items, search) {
        var result = [];
        angular.forEach(items, function (value, key) {
            angular.forEach(value, function (value2, key2) {
                if (value2 === search) {
                    result.push(value2);
                }
            })
        });
        return result;

    }
});

And that fiddle: http://jsfiddle.net/NqA8d/5/

Comments