[英]How can I find the sum of of Similar array object values and separate them based on their values
I have the following array object我有以下数组对象
[{ count: 2, created_data: "2022 07 19" },
{ count: 4, created_data: "2022 07 19" },
{ count: 4, created_data: "2022 07 19" },
{ count: 1, created_data: "2022 07 20" },
{ count: 1, created_data: "2022 07 20" }]
I would want to add the objects and get their sums based on the dates.我想添加对象并根据日期获取它们的总和。 So the result should look something like this
所以结果应该是这样的
[{
"2022 07 19" : 10,
"2022 07 20" : 2
}]
Just group by the desired property using reduce
method.只需使用
reduce
方法按所需属性进行分组。
var data = [{ count: 2, created_data: "2022 07 19" }, { count: 4, created_data: "2022 07 19" }, { count: 4, created_data: "2022 07 19" }, { count: 1, created_data: "2022 07 20" }, { count: 1, created_data: "2022 07 20" }] var result = [data.reduce(function(agg, item) { agg[item.created_data] = (agg[item.created_data] || 0) + item.count return agg }, {})] console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.