我试图创建一个简单的报告,我从ajax请求中获取条目,我想简单地按星期几对条目进行分组。例如,我希望得到一些简单的东西:
-----------------------------------
Monday - May 2nd - 2016
-----------------------------------
Entry 1
Description
Date: 2016-05-02 09:45
-----------------------------------
Entry 2
Description
Date: 2016-05-02 10:55
-----------------------------------
-----------------------------------
Tuesday - May 3rd - 2016
-----------------------------------
Entry 3
Description
Date: 2016-05-03 11:55
-----------------------------------
Entry 4
Description
Date: 2016-05-03 13:55
-----------------------------------
-----------------------------------
Wednesday - May 4th - 2016
-----------------------------------
No entries to report ....
-----------------------------------
etc ...
这是我到目前为止所做的事情的一个方面: https://jsfiddle.net/vLdn68ko/
我知道你可以通过Moment JS moment().format('dddd');
获得一周中的哪一天,但是我遇到的问题是如何让逻辑工作以便它按星期几分组?不太清楚如何开始。有人有任何想法吗?
这是我到目前为止的代码:
$.ajax({url:"/SomeUrlBeginninWithSlash",
dataType: 'json',
cache: false,
success: function (data) {
$.each(data.d.results, function (index, incident) {
$('body').append(
"<table border='1'>"+
"<TR><TD>Entry ID is"+incident.ID+"</TD></TR>"+
"<TR><TD>Description: "+incident.Description+"</TD></TR>"+
"<TR><TD>Date: "+incident.Date+"</TD></TR>"+
"</table>"+
"<br><br>"
);
})
}
});
答案 0 :(得分:4)
您可以使用对象
按日期索引项目var items_by_date = {}; // declare an object that will have date indexes
data.d.results.map(function(item){
var item_date = moment(item.Date).format('YYYY-MM-DD');
// if the date index does not exist we need to create it
if(!items_by_date[item_date]) items_by_date[item_date] = [item];
// else we can just push the item on that array
else items_by_date[item_date].push(item);
})
console.log(items_by_date);
// now you can render how ever you need to