AngularJS计算ID等于的JSON数组中的项目数

时间:2015-01-08 19:55:19

标签: javascript json angularjs

我可以使用以下内容获取JSON数组中的大量文章的总数:

Home.html中

<div ng-controller="pfcArticleCountCtrl">Number of Articles {{articlecount.length}} items</div>

Controllers.js

// Count number of total articles
pfcControllers.controller('pfcArticleCountCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {
$scope.articlecount = pfcArticles.query();

}]);

Services.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)

如何按类别计算文章数量?

2 个答案:

答案 0 :(得分:2)

您可以使用reduce创建一个cat id为name的对象,并将其计为值:

$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

答案 1 :(得分:0)

首先对数组var data = [ ];(您的数据)进行排序

data.sort(sort);

function sort(a,b) {
  if (a.articlecategoryid < b.articlecategoryid)
     return -1;
  if (a.articlecategoryid > b.articlecategoryid)
    return 1;
  return 0;
  }

然后计算重复值

var current = null;
    var cnt = 0;
    for (var i = 0; i < data.length; i++) {
        if (data[i].articlecategoryid != current) {
            if (cnt > 0) {
                document.write('Category'+current+'-->'+cnt+ ' times<br>');
            }
            current = data[i].articlecategoryid;
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        document.write('Category'+current+'-->'+cnt+ ' times');
    }

请参阅here

中的示例