将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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)