如何在Angular中统计assigned_to嵌套数据的sub_impact类型数量
解决方案:统计嵌套数组中sub_impact的分类数量
要实现每条父记录下assigned_to数组里不同sub_impact值的统计,我们可以修改getLatestUser方法,遍历每个父记录的嵌套数组并计数。以下是具体实现步骤和代码:
1. 先明确数据结构(模拟你的db.json)
假设你的父记录结构大概是这样的(方便理解代码逻辑):
[ { "id": 1, "title": "项目A", "assigned_to": [ {"sub_impact": "Applicable"}, {"sub_impact": "Applicable"}, {"sub_impact": "Not Applicable"}, {"sub_impact": "FYI"} ] }, { "id": 2, "title": "项目B", "assigned_to": [ {"sub_impact": "Applicable"}, {"sub_impact": "FYI"} ] } ]
2. 修改getLatestUser方法(TypeScript示例)
在app.component.ts中,我们重写方法来统计每个父记录下的sub_impact分布:
// 可选:定义类型接口让结构更清晰(JS项目可省略) interface AssignedItem { sub_impact: 'Applicable' | 'Not Applicable' | 'FYI'; // 其他字段如user_id、name等根据你的实际结构添加 } interface ParentRecord { id: number; title: string; assigned_to: AssignedItem[]; // 其他父级字段 } // 修改后的getLatestUser方法 getLatestUser(records: ParentRecord[]) { // 遍历每条父记录,生成带统计结果的新数组 return records.map(record => { // 初始化三个状态的计数器 const impactCounts = { Applicable: 0, 'Not Applicable': 0, FYI: 0 }; // 遍历当前记录的assigned_to数组,累加对应状态的数量 record.assigned_to.forEach(item => { // 只统计我们关心的三个状态,忽略其他可能的值 if (impactCounts.hasOwnProperty(item.sub_impact)) { impactCounts[item.sub_impact as keyof typeof impactCounts]++; } }); // 返回原记录+统计结果的合并对象,方便后续使用 return { ...record, impactCounts }; }); }
3. 使用统计结果(模板示例)
在组件模板中,你可以直接访问每条记录的统计数据:
<div *ngFor="let record of processedRecords"> <h4>{{ record.title }}</h4> <ul> <li>Applicable: {{ record.impactCounts.Applicable }}</li> <li>Not Applicable: {{ record.impactCounts['Not Applicable'] }}</li> <li>FYI: {{ record.impactCounts.FYI }}</li> </ul> </div>
在组件类中,你可以这样调用方法并赋值:
processedRecords: ParentRecord[]; // 假设你从db.json加载数据到records变量后 this.processedRecords = this.getLatestUser(this.records);
4. 边界情况处理
- 如果某个父记录的
assigned_to数组为空,三个状态的计数都会是0,符合预期。 - 如果
sub_impact出现了需求外的其他值,代码会自动忽略,不会影响统计结果。
内容的提问来源于stack exchange,提问作者Kunal Vijan
相关产品推荐
相关产品推荐

