red
red

Reputation: 305

AngularJS Group By object property

I have this object:

  $scope.items = [{ 
    "category": { "code": "10", "description": "Movies" },
        "item": {"code": "421", "description": "Noriko's Dinner Table" }
                  },{ 
    "category": { "code": "10", "description": "Movies" },
        "item": {"code": "511", "description": "Avatar" }
                  },{ 
    "category": { "code": "45", "description": "Books" },
        "item": {"code": "93", "description": "Divergent" }
                  },{ 
    "category": { "code": "45", "description": "Books" },
        "item": {"code": "72", "description": "Sense and Sensibility" }
                  },{ 
    "category": { "code": "33", "description": "TV Shows" },
        "item": {"code": "11", "description": "The Walking Dead" }
                  },{ 
    "category": { "code": "33", "description": "TV Shows" },
        "item": {"code": "60", "description": "The Bates Motel" }
                  }];

and I am trying to group them so that the list can be neatly organized and viewable. Like this:

enter image description here

But as you can see, the category description appears on every item. What do I do?

  <ul>
    <li ng-repeat="item in items track by $id(item)"><div>{{item.category.description}}</div>{{item.item.description}}</li>
  </ul>

LIVE DEMO: http://plnkr.co/edit/mjek9xPo3ihBTiwW6U0V?p=preview

Upvotes: 0

Views: 1606

Answers (1)

ajmajmajma
ajmajmajma

Reputation: 14216

You want to do something like this :

<ul ng-repeat="(key, value) in items | groupBy: 'category.description'">
 {{ key }}
   <li ng-repeat="item in value">
     {{ item.item.description }} 
   </li>
</ul>

Take advantage of angulars built in groupBy and filter.

Upvotes: 3

Related Questions