gpt4 book ai didi

javascript - 使用 AngularJS 从数组中创建统计数据

转载 作者:行者123 更新时间:2023-11-28 00:48:31 25 4
gpt4 key购买 nike

我有一个如下所示的对象数组:

[
{
"date":"20/11/2014",
"time":"17.54.39",
"car":"369",
"driver":"Jenny",
"from":"Luna House",
"destination":"James Hotel",
"pax":"3",
"comment":"",
"commenttime":"",
"arrival":"17.54.45",
"inserted":true,
"cancelled":"",
"duration":"00:00:06"
},
{
"date":"23/11/2014",
"time":"10.54.39",
"car":"210",
"driver":"David",
"from":"Office",
"destination":"Airport",
"pax":"3",
"comment":"",
"commenttime":"",
"arrival":"11.01.45",
"inserted":true,
"cancelled":"",
"duration":"00:07:06"
}
]

我想做的是能够提供数据数组中的统计信息。像这样的事情:

enter image description here

数组中的每个对象都是一次旅行,汽车是“car:code”,路上时间是所有“duration:”12:34:56”的总和(这是一个 momentJS 对象)。

到目前为止,我已经能够使用以下代码创建一个列出所有唯一月份的对象:

var monthDict = {};

angular.forEach($scope.recordlist, function(record) {
var month = moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY');
monthDict[month] = monthDict[month] || [];
monthDict[month].push(record);
});

for (record in monthDict) {
var month = record;
for (item in monthDict[record]) {
monthDict[record][item]['month'] = month;
}
};

$scope.monthlist = monthDict;

enter image description here

问题是,我认为要完成我需要的任务,我必须从每个月数组中提取独特的汽车和驾驶员列表并将其推回。

这就是我认为我可能需要的结构:

November: {
Trips: [
Object 1 {}
Object 2 {}
]
Cars: [
369 [
Object 1 {}
]
210 [
Object 1 {}
]
]
Drivers: [
Jenny [
Object 1 {}
Object 2 {}
],
Mango [
Object 1 {}
Object 2 {}
]
]
}

所以基本上,为每个独特的月份创建一个对象,然后每个月为每辆独特的汽车创建一个数组,并为每个独特的驾驶员创建一个数组。

关于如何到达那里有什么建议吗?我担心这对我现在来说有点太先进了。

最佳答案

如果您使用lodash这更容易。这是一种实现方法:

HTML:

  <body ng-app="myApp">
<h1>Hello AngularJS!</h1>
<div ng-controller="myCtrl">
{{hello}}
<pre>{{data | json}}</pre>
<pre>{{data2 | json}}</pre>

<div ng-repeat="(monthName, monthValue) in data2">
<p class="month-header">{{monthName}}</p>
<table ng-repeat="(groupName, groupValue) in monthValue">
<tr>
<th>{{groupName}}</th>
<th>Trips</th>
<th>Duration</th>
</tr>
<tr ng-repeat="(tripName, tripValue) in groupValue">
<td>{{tripName}}</td>
<td>{{tripValue.trips}}</td>
<td>{{tripValue.duration}}</td>
</tr>
</table>
</div>
</div>
</body>

JS:

  var dataByMonth = _.groupBy($scope.data, function(record) { return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); });
console.log(dataByMonth);
dataByMonth = _.mapValues(dataByMonth, function(month) {
var obj = {};
obj.Cars = _.groupBy(month, 'car');
obj.Drivers = _.groupBy(month, 'driver');

_.each(obj, function(groupsValue, groupKey) {
obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
return _.reduce(groupValue, function(sum, trip) {
sum['trips']++;
//addDuration(sum.duration, car.duration);
return sum;
}, {trips: 0, duration: ''})
});
})

return obj;
});
console.log(dataByMonth);

plunker

关于javascript - 使用 AngularJS 从数组中创建统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27078776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com