javascript中对象数组中相似键的总和

javascript中对象数组中相似键的总和,javascript,arrays,knockout.js,grouping,Javascript,Arrays,Knockout.js,Grouping,我有一个对象数组,如下所示:- 0: {Id: 0, count1: 5, count2: 10, yearMonth: "201803"} 1: {Id: 0, count1: 10, count2: 0, yearMonth: "201804"} 2: {Id: 1, count1: 900, count2: 200, yearMonth: "201805"} 3: {Id: 0, count1: 10, count2: 0, yearMonth: "201806"} 4: {Id: 1,

我有一个对象数组,如下所示:-

0: {Id: 0, count1: 5, count2: 10, yearMonth: "201803"}
1: {Id: 0, count1: 10, count2: 0, yearMonth: "201804"}
2: {Id: 1, count1: 900, count2: 200, yearMonth: "201805"}
3: {Id: 0, count1: 10, count2: 0, yearMonth: "201806"}
4: {Id: 1, count1: 100, count2: 100, yearMonth: "201807"}
5: {Id: 1, count1: 100, count2: 2, yearMonth: "201808"}
我想对相似的键求和以得到 预期产出:

1: {Id: 0, count1: 25, count2: 10}
2: {Id: 1, count1: 1100, count2: 402}
是否可以使用任何数学运算或reduce或任何其他javascript方法来实现它


感谢您,您可以通过使用哈希表和键数组对所需值求和来减少数组

var data=[{Id:0,count1:5,count2:10,yearMonth:“201803”},{Id:0,count1:10,count2:0,yearMonth:“201804”},{Id:1,count1:900,count2:200,yearMonth:“201805”},{Id:0,count1:10,count2:0,yearMonth:“201806”},{Id:1,count1:100,count2:100,yearMonth:“201807”},{Id:1,count1:100,count2:100,yearMonth:"201808" }],
键=['count1','count2'],
分组=对象.值(数据.减少((结果,对象)=>{
结果[object.Id]=结果[object.Id]|{Id:object.Id};
keys.forEach(key=>result[object.Id][key]=(result[object.Id][key]| | 0)+object[key]);
返回结果;
},Object.create(null));
console.log(分组);

。作为控制台包装{max height:100%!important;top:0;}
和knockout,您可以使用一系列计算属性来获得所需的(UI?)格式

免责声明:我假设此列表不会包含数千项

1.分组 第一步是从项目列表(
ko.observearray([])
)转到按id分组的计算对象:

//搜索“groupbyjavascript”以解释此函数
constgroupby=(prop,xs)=>xs.reduce(
(acc,x)=>Object.assign(acc,{[x[prop]]:(acc[x[prop]]| |[).concat(x)}),{}
);
常数项=ko.observearray([]);
const itemsbyd=ko.pureComputed(()=>
groupBy(“Id”,items())
);
itemsbyd.subscribe(console.log);
项目([{Id:0,count1:5,count2:10,yearMonth:“201803”},{Id:0,count1:10,count2:0,yearMonth:“201804”},{Id:1,count1:900,count2:200,yearMonth:“201805”},{Id:0,count1:10,count2:0,yearMonth:“201806”},{Id:1,count1:100,count2:100,yearMonth:“201807”},{Id:1,count1:100,count2:100,yearMonth:<>

是否可以使用任何数学运算或reduce或任何其他javascript方法来实现它?
-是的,@Sac。您的问题被否决的原因是您的问题并不表示您试图自己解决此问题。您可能会发现阅读帮助指南很有用。您写道:不到25分钟就完成了吗?:谢谢你的时间和努力,这确实对我有用。:-)