jQuery如何实现对象数组按多字段分组并对amount字段求和
jQuery 实现数组按指定字段分组合并amount
核心逻辑是借助临时对象做分组索引,将type、thick、width、height四个字段组合为唯一分组键,遍历过程中同组数据累加amount值,最终提取分组结果即可。
完整实现代码
var array = [ { type: "alu", thick : 1 ,width:1000, height:2000 , amount: 50 }, { type: "alu", thick : 1 ,width:1000, height:2000, amount: 30 }, { type: "alu", thick : 1.5 ,width:1000, height:2000, amount: 20 }, { type: "metal", thick : 2 ,width:1500, height:3000, amount: 15 } ]; var groupStore = {}; $.each(array, function(_, item) { // 用分隔符拼接四个字段生成分组key,避免不同字段值拼接产生歧义 var key = [item.type, item.thick, item.width, item.height].join('_'); if (groupStore[key]) { // 已存在同组数据,直接累加amount groupStore[key].amount += item.amount; } else { // 新分组,拷贝当前对象存入存储,避免修改原数组引用 groupStore[key] = $.extend({}, item); } }); // 从分组存储中提取最终结果数组 var result = $.map(groupStore, function(val) { return val; });
运行后result的值和预期输出完全一致。
注意事项
- 分组key拼接时必须加分隔符,否则会出现字段值交叉拼接导致key重复的bug,比如
type:'a', thick:1和type:'a1', thick:''如果直接无分隔符拼接会生成相同字符串,导致错误分组。 - 如果不需要保留原始数组的对象不被修改,可以去掉
$.extend拷贝逻辑,直接存储item即可,性能会稍好一点。
内容的提问来源于stack exchange,提问作者MASTER KOURANI
相关产品推荐
相关产品推荐

