slevin slevin - 1 month ago 15
AngularJS Question

Sort multidimensional JSON in angular

I get JSON from a database and its structure is like this:

"data": [
{
"category": "1",
"description": "hello"
}
]


description
and
category
are all dynamic, so I can have 5 objects with
category:1
and 2 with
category:3
etc. Or I could have 3 objects with
category:20
and 25 objects with
category:8
.

I want to create HTML elements like this:

Category 1
....
....
....

Category 3
....
....


I can create a string like this:

$scope.hello = [];
angular.forEach(data.data, function(value, key) {
$scope.hello.push(value.category+" "+value.description)
}


so that it will output:

Category 1 hello
Category 1 hi
Category 1 bye
Category 3 sup
Category 3 yo


But how will I turn this to:

Category 1
hello
hi
bye

Category 3
sup
yo

SSH SSH
Answer

use groupBy of angular.filter module for more info see this answer . How can I group data with an Angular filter?

var app = angular.module("app",['angular.filter'])
app.controller('ctrl',['$scope', function($scope){
        $scope.data = [
                {
                  "category": "1",
                  "description": "hello"
                },
          {
                  "category": "1",
                  "description": "hi"
                },
          {
                  "category": "3",
                  "description": "hai"
                },
          {
                  "category": "1",
                  "description": "hello"
                },
          {
                  "category": "3",
                  "description": "hello"
                },
          {
                  "category": "1",
                  "description": "hai"
                }
   ]
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
   <ul ng-repeat="(key, value) in data | groupBy: 'category'">
      category: {{ key }}
      <li ng-repeat="d in value |orderBy:'description'">
          {{ d.description }} 
      </li>
   </ul>      
</div>