通过数组中的多个属性对对象进行分组,然后对其值求和

通过数组中的多个属性对对象进行分组,然后对其值求和,第1张

通过数组中的多个属性对对象进行分组,然后对其值求和

将Array#reduce与帮助器对象一起使用可以对相似的对象进行分组。对于每个对象,检查合并的

shape
和是否
color
存在于帮助器中。如果不是,请使用Object#assign添加到帮助器中以创建对象的副本,然后将其压入数组。如果是这样,请将其值添加到
used
instances

var arr = [{"shape":"square","color":"red","used":1,"instances":1},{"shape":"square","color":"red","used":2,"instances":1},{"shape":"circle","color":"blue","used":0,"instances":0},{"shape":"square","color":"blue","used":4,"instances":4},{"shape":"circle","color":"red","used":1,"instances":1},{"shape":"circle","color":"red","used":1,"instances":0},{"shape":"square","color":"blue","used":4,"instances":5},{"shape":"square","color":"red","used":2,"instances":1}];var helper = {};var result = arr.reduce(function(r, o) {  var key = o.shape + '-' + o.color;  if(!helper[key]) {    helper[key] = Object.assign({}, o); // create a copy of o    r.push(helper[key]);  } else {    helper[key].used += o.used;    helper[key].instances += o.instances;  }  return r;}, []);console.log(result);

如果你可以使用ES6,您可以使用地图收集的值,然后将其转换回一个数组蔓延的地图#值:

const arr = [{"shape":"square","color":"red","used":1,"instances":1},{"shape":"square","color":"red","used":2,"instances":1},{"shape":"circle","color":"blue","used":0,"instances":0},{"shape":"square","color":"blue","used":4,"instances":4},{"shape":"circle","color":"red","used":1,"instances":1},{"shape":"circle","color":"red","used":1,"instances":0},{"shape":"square","color":"blue","used":4,"instances":5},{"shape":"square","color":"red","used":2,"instances":1}];const result = [...arr.reduce((r, o) => {  const key = o.shape + '-' + o.color;  const item = r.get(key) || Object.assign({}, o, {    used: 0,    instances: 0  });  item.used += o.used;  item.instances += o.instances;  return r.set(key, item);}, new Map).values()];console.log(result);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5011579.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存