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

AngularJS count number of items in JSON array where ID equals

我可以使用以下方法获取 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)

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

首先对数组进行排序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

中的示例

您可以使用 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