json - 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]++);
})
}
谢谢
解决方案
您可以做一个简单的循环并添加另外两个变量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]++);
推荐阅读
- c# - 在新窗口中打开 TabItem
- javascript - JS/CSS 如何在变换中间改变背景颜色?
- javascript - 检查对象是否包含数组
- algorithm - 如何找出最接近一组点的两个点?
- nativescript - 看不到 nativescript-vue popup #ref-nativescript-popup 插件
- python - 如何测试变量是否属于特定类?
- sql - MS SQL - 从多对多表中选择数据,其中列的值与所有给定值匹配
- sql - 如何将此 Oracle 脚本转换为 MSSQL?
- laravel - 如何循环和比较从单个视图 Laravel 传递的多个数据
- whitespace - 如何删除文件名前面的空格,同时在 Windows 10 的 3000 个文件中保留其他空格