I have a an array with objects looking like this:
我有一个对象像这样的数组:
{
"date":"11/11/2014",
"time":"17.20.37",
"car":"396",
"driver":"Jenny",
"from":"Old Office",
"destination":"Log WH",
"pax":"3","comment":"",
"commenttime":"",
"arrival":"17.20.48",
"inserted":true,
"cancelled":"",
"duration":"00:00:11"
}
What I am trying to accomplish is to automatically list the items by month, like the following:
我要做的是按月自动列出项目,如下所示:
-November 2014
ng-repeat with records from 11-14
-October 2014
ng-repeat with records from 10-14
I know this involves going through the array and getting together all items that have a common property (the same month and year).
我知道这包括遍历数组并将所有具有公共属性的项(相同的月份和年份)聚集在一起。
I'm already doing that with the car code, listing the different unique car codes like so:
我已经用汽车代码做过了,列出了不同的独特的汽车代码如下:
var carsDict = {};
angular.forEach($scope.recordlist, function(record) {
carsDict[record.car] = carsDict[record.car] || [];
carsDict[record.car].push(record);
});
$scope.carstats = carsDict;
This piece of code creates an array of objects for every unique car code (record.car
).
这段代码为每个唯一的car代码(record.car)创建一个对象数组。
I could do the same with the record.date
property (which is a moment() object) but it would group together all objects that have the same exact date in common, not the same month and year.
我也可以用这张唱片。date属性(它是一个moment()对象),但是它会将所有具有相同确切日期的对象组合在一起,而不是相同的月份和年份。
Any idea about how to accomplish this?
你知道怎么做吗?
EDIT
编辑
Here's a JSFiddle of where I got until now. In the example I list the car codes, trips (every object in the array is a trip) and time in the road (sum of all record.duration) for each car.
这是我到现在为止的资料。在这个例子中,我列出了每辆车的车号、行程(数组中的每个对象都是一个行程)和路上的时间(所有记录的总和。持续时间)。
Right now it makes the calculation and shows the results for all the objects of the recordlist
, but the next step is to do the same, but by list it automatically by month.
现在,它进行计算并显示记录列表中所有对象的结果,但是下一步也是这样做的,但是按月自动列出。
1 个解决方案
#1
2
For each records list you need to create a year-month dictionary (2014-11):
对于每个记录列表,您需要创建一个年度月字典(2014-11):
var monthsDict = {};
angular.forEach(records, function(record) {
var month = moment(record.date).format('YYYY-MM');
monthsDict[month] = monthsDict[month] || [];
monthsDict[month].push(record);
});
You can sort it if you need like so:
如果你需要,你可以这样分类:
var sortDates = function(a,b) { return moment(a.date) - moment(b.date); };
angular.forEach(monthsDict, function(month) {
month.sort(sortDates);
});
#1
2
For each records list you need to create a year-month dictionary (2014-11):
对于每个记录列表,您需要创建一个年度月字典(2014-11):
var monthsDict = {};
angular.forEach(records, function(record) {
var month = moment(record.date).format('YYYY-MM');
monthsDict[month] = monthsDict[month] || [];
monthsDict[month].push(record);
});
You can sort it if you need like so:
如果你需要,你可以这样分类:
var sortDates = function(a,b) { return moment(a.date) - moment(b.date); };
angular.forEach(monthsDict, function(month) {
month.sort(sortDates);
});