如何将对象数组中相同公共键对应的value值聚合为数组?
同tharea键的数组聚合实现方案
- 之前使用
flatMap得不到预期结果的核心原因:flatMap的作用是对数组每一项做映射后,把返回的嵌套数组做单层扁平化,本身不具备按公共键做分组累加的能力,属于API适用场景错配,自然无法得到正确的聚合结果。 - 推荐实现:基于
reduce的通用分组方案
这个方案只需要遍历一次原始数组,兼容性最强,哪怕原始数组里混杂多个不同的tharea类型(比如肿瘤、神经领域的条目),也能自动完成分组聚合,不需要为特定tharea硬写逻辑。
代码如下:
最终输出的// 原始输入数组 const rawData = [ {tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, {tharea: "Rare Disease", value: 4090880}, {tharea: "Rare Disease", value: 1657600} ] // 聚合逻辑 const aggregatedData = Object.values( rawData.reduce((groupMap, currentItem) => { const thareaKey = currentItem.tharea // 分组映射表中不存在当前tharea时,先初始化对应分组结构 if (!groupMap[thareaKey]) { groupMap[thareaKey] = { tharea: thareaKey, value: [] } } // 将当前条目的value push到对应分组的value数组中 groupMap[thareaKey].value.push(currentItem.value) return groupMap }, {}) )aggregatedData结构和目标要求完全一致。 - 直观写法(适合小数据量场景)
如果更习惯用映射、过滤的常规思路,也可以先提取所有不重复的tharea列表,再逐组匹配对应的value值生成条目,逻辑更直白但需要多次遍历原始数组:
// 提取去重后的tharea列表 const uniqueThareas = [...new Set(rawData.map(item => item.tharea))] const aggregatedData = uniqueThareas.map(tharea => ({ tharea, // 匹配当前tharea下的所有value值组成数组 value: rawData.filter(item => item.tharea === tharea).map(i => i.value) }))
内容的提问来源于stack exchange,提问作者Avdhut
相关产品推荐
相关产品推荐

