如何迭代无序的JSON数据并排序到数组中

时间:2022-06-19 15:59:07

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:

我正在从json对象结构中的API中获取数据。问题是这个json不按顺序排列,我理解它本质上是无序的。我想知道如何迭代这些键并通过将它们放入数组中对这些数据进行排序(我已经使用ng-repeat将它们打印在表中但是它们是随机排列的,所以我的最终目标是让它们显示在按日期排序)。以下是结构示例:

{
    "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

1 个解决方案

#1


1  

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

你是对的,orderBy不支持对象。所以只需先将对象转换为数组。

$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

然后使用orderBy

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

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

#1


1  

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

你是对的,orderBy不支持对象。所以只需先将对象转换为数组。

$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

然后使用orderBy

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

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