1

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
3
  • Are all your dates guaranteed to be from the same year? If so you can take advantage of Array.prototype.sort. Commented Apr 11, 2016 at 3:24
  • why not use orderBy filter? Commented Apr 11, 2016 at 3:25
  • I tried but that only works for arrays. My structure is in json. The dates are not guaranteed to be from same year Commented Apr 11, 2016 at 3:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

The order will not work if your dates are 01/05/2016, 01/01/2015, 01/03/2016
What happens if one of the value is 01/03/2015?
Will sorted as 01/01/2016 01/03/2015 01/05/2016
Thank you, just finished it up and it looks like it is working. I have not tested it on different years..so will have to look into that. Any possible solutions to handle that case?
since the date is a just a string, you need to convert it into a proper Date object in order to sort it properly. just do it inside of the mapper. i.e. return {key : new Date(k), value : $scope.testObj[k]};. Anyway, you can convert the key to whatever you like and sort it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.