Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular filter a object by its 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.

like image 821
Conqueror Avatar asked Nov 08 '13 01:11

Conqueror


People also ask

What is the correct way to apply filter in angular?

Filters can be added to expressions by using the pipe character | , followed by a filter.

How do you filter objects with keys?

JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.


1 Answers

Little late to answer, but this might help :

If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }"> 

You can also filter on multiple properties of an object just by adding them to your filter object:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }"> 

The syntax of 'not equals' is just a little off, try the following:

<div ng-repeat="thing in things | filter: { properties: { title: '!' + title_filter } }"> 
like image 135
Vaibhav Pachauri Avatar answered Oct 05 '22 23:10

Vaibhav Pachauri