正在阅读:
- 首页 » 开发运维 » 前端 » js vue实现GROUP BY分类汇总并汇总数值
js vue实现GROUP BY分类汇总并汇总数值
js实现GROUP BY分类汇总并汇总数值
原始数据如:
arrTemp = [{ "operator": "2", "testNumber": 22 }, { "operator": "3", "testNumber": 33 }, { "operator": "1", "testNumber": 11 }, { "operator": "4", "testNumber": 44 }, { "operator": "2", "testNumber": 22 }, { "operator": "4", "testNumber": 44 }, { "operator": "1", "testNumber": 11 }, { "operator": "3", "testNumber": 33 } ]
创建一个工具函数
groupBy(arrTemp) { let keyContainerTemp = {} // 以key进行分组的临时对象 arrTemp.forEach((item) => { keyContainerTemp[item.operatorKey] = keyContainerTemp[item.operatorKey] || [] keyContainerTemp[item.operatorKey].push(item) }) console.log(keyContainerTemp) let keysTemp = Object.keys(keyContainerTemp) keysTemp.forEach((keysItem) => { let count = 0 keyContainerTemp[keysItem].forEach((item) => { count += item.testNumber // 遍历每种Key对应的数量汇总 }) this.arrGroupByResult.push({ operatorKey: keysItem, total: count }) }) console.log(this.arrGroupByResult) }
执行后,会将数组对象中,以operator为键值重复的会合并,testNumber 的值会累加。
[{ "operator": "1", "testNumber": 22 }, { "operator": "2", "testNumber": 44 }, { "operator": "3", "testNumber": 66 }, { "operator": "4", "testNumber": 88 }]
该日志由 bemender 于 2022年05月28日 发表
转载请注明文本地址:https://www.bemhome.com/post/152.html