JS中如何按多字段分组求和生成计算后的JSON数组
JS 按name和location双字段分组求和实现方案
你可以通过临时Map存储分组聚合结果的方式实现需求,核心逻辑是用name+location拼接生成唯一分组标识,遍历原始数据时同组数据做数值累加,最终转换为目标数组格式即可,完整实现代码如下:
// 原始数据 const stuff = [ {"name": "shark", "location": "somewhere", "number":10}, {"name": "shark", "location": "somewhereelse", "number":50}, {"name": "shark", "location": "somewhere", "number":25}, {"name": "turtle", "location": "anotherplace", "number":1}, {"name": "elephant", "location": "greatplace", "number":50}, {"name": "elephant", "location": "greatplace", "number":75} ]; const groupMap = new Map(); stuff.forEach(item => { // 生成唯一分组键,分隔符|可替换为其他不会出现在name/location字段的字符避免冲突 const key = `${item.name}|${item.location}`; groupMap.has(key) ? groupMap.get(key).number += item.number : groupMap.set(key, { ...item }); }); // 转换为目标数组格式,可直接传入Plotly.js绘图函数使用 const computed = Array.from(groupMap.values());
执行上述代码后得到的computed变量完全符合你要求的输出格式。
内容的提问来源于stack exchange,提问作者DLBPointon
相关产品推荐
相关产品推荐

