我有一个看起来像这样的对象:
Object {391:Array[1], 396: Array[2]}
391:
Array[1]
0:
arrival: "17.43.49"
car: "391"
date: "11/11/2014"
duration: "00:00:06"
time: "17.43.43"
396:
Array[2]
0:
arrival: "17.20.48"
car: "396"
date: "11/11/2014"
duration: "00:00:11"
time: "17.20.37"
1:
arrival: "17.21.27"
car: "396"
date: "11/11/2014"
duration: "00:00:17"
time: "17.21.10"
它由以下函数构成:
var carsDict = {};
angular.forEach($scope.recordlist, function(record) {
carsDict[record.car] = carsDict[record.car] || [];
carsDict[record.car].push(record);
});
$scope.carstats = carsDict;
有没有办法使用AngularJS我可以从数组中的每个对象添加一个substract属性?
例如,在上面的示例中,每个对象都是来自特定汽车的旅行(391有一次旅行,396有两次旅行)。现在我使用ng-repeat列出汽车代码和行程数,如下所示:
<div class="row" ng-repeat="carcode in carstats">
<div class="col-md-4">{{carcode[0].car}}</div>
<div class="col-md-4">{{carcode.length}}</div>
</div>
我想要做的是弄清楚每辆车的总持续时间,所以我需要能够将每个阵列中每个对象的所有持续时间属性加在一起。
在上面的示例中,每个数组必须最终具有属性totalduration
,该属性是数组所有对象中所有持续时间属性的总和。例如,第二个数组应该有 396.totalduration =(持续时间:&#34; 00:00:11&#34;)+(持续时间:&#34; 00:00:17&#34;)< /强>
任何提示?
答案 0 :(得分:1)
我建议在控制器内进行总和计算:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var carsDict = {
391: [
{
arrival: "17.43.49",
car: "391",
date: "11/11/2014",
duration: "00:00:06",
time: "17.43.43"
}
],
396: {
0: {
arrival: "17.20.48",
car: "396",
date: "11/11/2014",
duration: "00:00:11",
time: "17.20.37",
},
1: {
arrival: "17.21.27",
car: "396",
date: "11/11/2014",
duration: "00:00:17",
time: "17.21.10"
}
}
};
for (record in carsDict) {
var totalduration = '';
for (item in carsDict[record]) {
// get totalduration figured out..
totalduration += carsDict[record][item].duration; // need to account for sum using time format here
}
for (item in carsDict[record]) {
// now add totalduration to each record
carsDict[record][item]['totalduration'] = totalduration;
// to add a new value to the individual item
carsDict[record][item]['newvalue'] = 'anything you want';
// to remove a value (I prefer changing to undefined)
carsDict[record][item].arrival = undefined;
}
};
$scope.test = carsDict;
}