首页 > 解决方案 > json/rest api:如何获取与特定值匹配的节点数

问题描述

我在 db.json 中有数据(4000 多条记录)。我正在使用角度 httpclient 来显示数据(使用 CRUD 操作)。

其中一列是性别。现在,我想知道男性、女性和其他人的数量。

我需要在我的打字稿中写什么才能知道所有记录中男性、女性和其他人的计数和显示数量?

app.component.html

{{impactCount.applicable}}  
{{impactCount.fyi}}

app.component.ts

impactCount = {
    applicable: 0,
    fyi: 0
  }

     getLatestUser() {
    this.commonService.getAllUser().subscribe((response) => {
      this.allUser = response;
      this.totalRecords = this.allUser.length;
      this.allUser.forEach(row => this.impactCount[row.impact]++);
    })
  }

谢谢

标签: jsonangulartypescript

解决方案


您可以做一个简单的循环并添加另外两个变量maleCount,称为femaleCount

genderCount = {
    male: 0;
    female: 0;
    other: 0;
}

getLatestUser() { 
    this.service.getAllUser().subscribe((response) => { 
        this.allUser = response; 
        this.totalRecords = this.allUser.length;

        this.allUser.forEach(row => {
            if (row.gender === 'Male') {
                this.genderCount.male++;
            } else if (row.gender === 'Female') {
                this.genderCount.female++;
            } else {
                this.genderCount.other++;
            }
        });
    }); 
}

或者,如果数据库中的性别选项将是“男性”、“女性”和“其他”,您可以像这样访问它们并减少代码。

this.allUser.forEach(row => this.genderCount[row.gender]++);

推荐阅读