如何基于value与parentId关联统计团队对应职责数量?
问题与解决方案
需求
现有包含teams和duty嵌套数组的JSON数据,需要根据teams.value和duty.parentId的对应关系,统计每个团队对应的职责数量,最终输出如下格式的结果:
{ "Team A": 2, "Team B": 3 }
原始JSON数据
{"jsonArray":[ { "teams":[ { "text":"Team A", "id":1, "value":500, "parentId":333 }, { "text":"Team B", "id":2, "value":600, "parentId":444 } ], "duty":[ { "text":"Meetings", "id":11, "value":100, "parentId":500 }, { "text":"Lunch", "id":12, "value":101, "parentId":500 }, { "text":"Time Cards", "id":13, "value":102, "parentId":600 }, { "text":"Parking", "id":14, "value":103, "parentId":600 }, { "text":"Breakfast", "id":15, "value":104, "parentId":600 } ] } ]}
当前代码问题
现有代码仅能统计teams数组本身的对象数量,无法关联duty数组完成匹配统计。
解决方案代码
高效版(适合大数据量)
newJsonData() { // 提取目标数据(根据结构,jsonArray为单元素数组) const { teams, duty } = this.jsonArray[0]; // 构建团队value到团队名称的映射表 const teamValueMap = teams.reduce((map, team) => { map[team.value] = team.text; return map; }, {}); // 统计每个parentId对应的职责数量 const dutyCountMap = duty.reduce((counts, item) => { const parentId = item.parentId; counts[parentId] = (counts[parentId] || 0) + 1; return counts; }, {}); // 转换为预期的结果格式 const result = {}; for (const [value, count] of Object.entries(dutyCountMap)) { const teamName = teamValueMap[value]; if (teamName) { result[teamName] = count; } } console.debug("dutyCount", result); return result; }
直观版(适合小数据量)
newJsonData() { const { teams, duty } = this.jsonArray[0]; const result = teams.reduce((res, team) => { // 过滤出当前团队对应的所有职责 const matchedDuties = duty.filter(dutyItem => dutyItem.parentId === team.value); res[team.text] = matchedDuties.length; return res; }, {}); console.debug("dutyCount", result); return result; }
代码说明
- 高效版:先通过两次
reduce分别构建映射表和统计职责数量,最后转换格式,时间复杂度为O(n+m),数据量大时性能更优。 - 直观版:直接遍历每个团队,过滤对应职责并统计数量,逻辑简单易懂,时间复杂度为O(n*m),适合数据规模较小的场景。
内容的提问来源于stack exchange,提问作者Sunny
相关产品推荐
相关产品推荐

