Ad

How Can I Iterate Over Unordered JSON Data And Sort Into An Array

- 1 answer

I'm grabbing data from an API which is in a json object structure. The problem is that this json is not in order and I understand is unordered by nature. I was wondering how I could iterate over these keys and sort this data by putting them in an array (I already have them printing out in a table using ng-repeat but they are in random order so my end goal is to have them displayed in order by date). Here is an example of the structure:

{
    "01/05/2016": {
         "Something1": {},
         "Something2": {}      
     },
    "01/01/2016": {
         "Something1": {},
         "Something2": {}      
     },
    "01/03/2016": {
         "Something1": {},
         "Something2": {}      
     }
}

 <tr ng-repeat="(key,value) in metrics_data">
          <td align="center">{{key}}</td>
          //and then I do another ng-repeat right here for values
Ad

Answer

You are right about the fact that orderBy doesn't support object. so just convert the object into array first.

$scope.testObj = {
"01/05/2016": {
     "Something1": {},
     "Something2": {}      
 },
"01/01/2016": {
     "Something1": {},
     "Something2": {}      
 },
"01/03/2016": {
     "Something1": {},
     "Something2": {}      
 }
};

$scope.testObjArray = Object.keys($scope.testObj).map(
                     function(k) { 
                         return {key: k, value: $scope.testObj[k]} 
                     });

then use orderBy

ng-repeat="obj in testObjArray | orderBy : 'key'"

see http://plnkr.co/edit/AhRWwhp0a5gndC7RByqt?p=preview

Ad
source: stackoverflow.com
Ad