我可以使用以下命令获取 JSON 数组中文章的总数:
首页.html
<div ng-controller="pfcArticleCountCtrl">Number of Articles {{articlecount.length}} items</div>
Controller .js
// Count number of total articles
pfcControllers.controller('pfcArticleCountCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {
$scope.articlecount = pfcArticles.query();
}]);
服务.js
// Articles by ID
pfcServices.factory('pfcArticles', ['$resource', function ($resource) {
return $resource('https://myrestcall.net/tables/articles/:articleID', { articleID: '@id' },
{
'update': { method:'PATCH'}
}
);
}]);
但我还想按类别显示文章数量。下面是一个 JSON 返回示例:
[
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D4",
"articletitle": "artilce1",
"articlecategoryid": 1,
"articlesummary": "article 1 summary. "
},
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D5",
"articletitle": "artilce2",
"articlecategoryid": 2,
"articlesummary": "article 2 summary. "
},
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D6",
"articletitle": "artilce3",
"articlecategoryid": 3,
"articlesummary": "article 3 summary. "
},
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D7",
"articletitle": "artilce4",
"articlecategoryid": 1,
"articlesummary": "article 3 summary. "
},
]
在本例中,总计数为 4,但对于类别 1,它应该为 2。我想在页面上显示它,如下所示:
类别 1 (2) 类别 2 (1) 类别 3 (1)
文章总数(4)
如何按类别统计文章数量?
最佳答案
您可以使用reduce创建一个以cat id为名称并以count为值的对象:
$scope.articleByCat = articles.reduce(function (prev, item) {
if ( !! prev[item.articlecategoryid]) {
//category already exist -> increment
prev[item.articlecategoryid]++;
} else {
//category does not exist -> init
prev[item.articlecategoryid] = 1;
}
return prev;
}, {});
您通过范围公开它并通过 ng-repat 显示它
<div ng-app='article' ng-controller='ArticleController'>
<ul>
<li ng-repeat='(key, value) in articleByCat'>Category {{key}} : {{value}}</li>
</ul>
</div>
工作中jsfiddle
关于javascript - AngularJS 计算 JSON 数组中 ID 等于的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27848462/