我有一个包含一些数据的 JSON 文件,例如:
$scope.expenses = [
{
"amount": "100",
"SpentOn": "19/04/2014",
"IsExpensable": true,
},
{
"amount": "200",
"SpentOn": "20/04/2014",
"IsExpensable": true,
},
{
"amount": "50",
"SpentOn": "01/01/2014",
"IsExpensable": true,
},
{
"amount": "350",
"SpentOn": "01/09/2013",
"IsExpensable": false,
}
];
我正在尝试编写一个循环遍历上述内容的 Angular 函数,当 IsExpensable= true 时,然后对 mm 和 yyyy 进行计数,以确定该月产生了多少费用。因此,在上面的示例中,2014 年 4 月有 2 个。2010 年 1 月有 1 个。
这是我的 JS:
$scope.MyDateFilterFunction = function () {
var data = [];
var dataMonth = [];
var dataYear = [];
var Jan = 0;
var Feb = 0;
var Mar = 0;
var Apr = 0;
var May = 0;
var May = 0;
var Jun = 0;
var Jul = 0;
var Aug = 0;
var Sep = 0;
var Oct = 0;
var Nov = 0;
var Dec = 0;
angular.forEach($scope.expenses, function (value, key) {
if (value.IsExpensable) {
angular.forEach($scope.expenses, function (value, key) {
data = value.SpentOn.split('/');
dataMonth = data[1];
dataYear = data[2];
var count = (dataMonth.split("04").length - 1)
console.log("April occurances" + count.length);
// Add count to var Apr
});
}
});
return data;
};
我的 HTML:
<td ng-repeat="exp in MyDateFilterFunction ()">
{[{exp}]}
</td>
<小时/>
更新:
已添加:
if (dataMonth == "04") {
Apr = Apr + 1;
console.log(Apr);
}
但是控制台输出是: 1 2 3 4 1 2 3 4 1 2 3 4
<小时/>通过删除第二个 angular.forEach
语句解决
最佳答案
来自迈克(基于下划线)的回答:
“想象一下用您自己的代码编写一个解决方案” - 接受挑战!
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$scope.groupped = $scope.expenses
/* Only give me expensable items */
.filter(function (exp) {
return exp.IsExpensable;
})
/* Determine each item's group (with friendly display name) */
.map(function (exp) {
var dateArr = exp.SpentOn.split('/');
var groupValue = '' + months[parseInt(dateArr[1]) - 1] +
' ' + dateArr[2];
return groupValue;
})
/* Map group-names to items-count */
.reduce(function (groupped, groupValue) {
groupped[groupValue] = (groupped[groupValue] || 0) + 1;
return groupped;
}, {});
<div ng-repeat="(time, count) in groupped">
{{time}}: {{count}}
</div>
如果(无论出于何种原因)您更喜欢数组而不是对象:
$scope.groupped = ...;
$scope.grouppedArr = Object.keys($scope.groupped).map(function (key) {
return {name: key, count: $scope.groupped[key]};
});
<div ng-repeat="group in grouppedArr">
{{group.name}}: {{group.count}}
</div>
<小时/>
另请参阅此 short demo
<小时/><子>
注1:
在这两种情况下(普通 JS、下划线)都需要额外的逻辑才能按月份索引对结果进行排序。
<子>
注2:
如果您计划支持旧版本的浏览器(是的,我的意思是 IE < 9),您可能需要使用 underscore 或 lodash 等库作为后备。
关于javascript - 计算出现次数并递增值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23805426/