JSON为AngularJs中的每个方法重新分组

时间:2017-02-15 14:24:55

标签: angularjs

我是角色新手,我想重新组合一个JSON。是否可以使用angular.forEach()方法?

[  
   {  
      "doc":{  
         "Title":"Main",
         "name":"Ajith",
         "Day":"03",
         "count":3
      }
   },
   {  
      "doc":{  
         "Title":"starters",
         "name":"Saji",
         "Day":"01",
         "count":39
      }
   },
   {  
      "doc":{  
         "Title":"desert",
         "name":"Sajeeb",
         "Day":"02",
         "count":63
      }
   },
   {  
      "doc":{  
         "Title":"Main",
         "name":"Suith",
         "Day":"03",
         "count":3
      }
   },
   {  
      "doc":{  
         "Title":"starters",
         "name":"Manu",
         "Day":"01",
         "count":9
      }
   }
]

我希望输出应该如下。

{  
   "order":[  
      {  
         "Day":"01",
         "Title":"starters",
         "items":[  
            {  
               "name":"Saji",
               "count":39
            },
            {  
               "name":"Manu",
               "count":9
            }
         ]
      },
      {  
         "Day":"02",
         "Title":"desert",
         "items":[  
            {  
               "name":"Sajeeb",
               "count":63
            }
         ]
      },
      {  
         "Day":"03",
         "Title":"Main",
         "items":[  
            {  
               "name":"Ajith",
               "count":3
            },
            {  
               "name":"Suith",
               "count":3
            }
         ]
      }
   ]
}

使用angular.forEach()方法重新组合。 请帮忙。感谢。

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/9fwtm0a0/4/

var days = [];
arr.forEach(function(d) {
    var day = parseInt(d.doc.Day);
    var item = { name: d.doc.name, count: d.doc.count };

    if (days[day])
        days[day].items.push(item);
  else
    days[day] = { Day: '0' + day, Title: d.doc.Title, items: item]};
});

days.sort(function (x, y) {
    return parseInt(x.Day) > parseInt(y.Day);
});

var eventsinOrder = { order: days };

你真的不需要Angular forEach,但你可以轻松地将其替换为:

var days = [];
angular.forEach(arr, function (val, key) {
    var day = parseInt(val.doc.Day);
    var item = { name: val.doc.name, count: val.doc.count };

    if (days[day])
        days[day].items.push(item);
    else
        days[day] = { Day: '0' + day, Title: val.doc.Title, items: [item]};
});

days.sort(function (x, y) {
    return parseInt(x.Day) > parseInt(y.Day);
});

var eventsinOrder = { order: days };

无论你走到哪里,你仍然需要使用sort函数(或任何等价函数)在你构建这个结果对象时执行排序。