[英]how to group by and total sum array of object in javascript?
After I use reduce()
to group the objects in an array by month-year:在我使用
reduce()
按月年对数组中的对象进行分组后:
let groupByMonth;
if (newlistTaskEvaluation) {
groupDataByMonth = newlistTaskEvaluation.reduce((groups, item) => {
groups[item.time] = [...groups[item.time] || [], item];
return groups;
}, {});
}
I have an array of event objects formatted by group month-year as follows:我有一组按组月-年格式化的事件对象,如下所示:
groupByMonth = {
'7-2020': [ //july
{
time: "7-2020",
task: [
{ code: "p1", value: 123 },
{ code: "p2", value: 234 },
]
},
{
time: "7-2020",
task: [
{ code: "p1", value: 345 },
{ code: "p2", value: 456 },
]
},
],
'8-2020': [ //august
{
time: "8-2020",
task: [
{ code: "p1", value: 567 },
{ code: "p2", value: 678 },
]
},
{
time: "8-2020",
task: [
{ code: "p1", value: 789 },
{ code: "p2", value: 999 },
]
},
]
}
How to group object of Array by key 'code', time and total sum by value?如何按“代码”键、时间和总和按值对数组的 object 进行分组?
Expected result:预期结果:
output = [
{
time: "7-2020", //total month 7-2020
task: [
{ code: "p1", valueSum: 468 }, // 123 + 345
{ code: "p2", valueSum: 690 }, // 234 +456
]
},
{
time: "8-2020",
task: [
{ code: "p1", valueSum: 1356 }, // 567 + 789
{ code: "p2", valueSum: 1677 }, // 999 +678
]
}
]
Please help me.请帮我。
You could try something like this你可以试试这样的
const output = Object.entries(groupByMonth).map(([time, datapoints]) => {
const codes = {}
const allTasks = datapoints.flatMap(point => point.task)
for (const { code, value } of allTasks) {
codes[code] = (codes[code] || 0) + value
}
return {
time,
tasks: Object.entries(codes).map(([code, value]) => ({ code, value }))
}
}
Though one downside is that the time complexity isn't perfect because of the structure of the data虽然一个缺点是由于数据的结构,时间复杂度并不完美
const groupByMonth = {
"7-2020": [
//july
{
time: "7-2020",
task: [
{ code: "p1", value: 123 },
{ code: "p2", value: 234 },
],
},
{
time: "7-2020",
task: [
{ code: "p1", value: 345 },
{ code: "p2", value: 456 },
],
},
],
"8-2020": [
//august
{
time: "8-2020",
task: [
{ code: "p1", value: 567 },
{ code: "p2", value: 678 },
],
},
{
time: "8-2020",
task: [
{ code: "p1", value: 789 },
{ code: "p2", value: 999 },
],
},
],
};
const result = Object.keys(groupByMonth).reduce((arr, key)=>{
const task = (groupByMonth[key]).reduce((acc, rec) => {
return [...acc, rec.task]
}, [])
const newObj = {time: key, task}
return [...arr, newObj]
}, [])
console.log(JSON.stringify(result, 2, 2))
You can get object's keys and when you iterate over them find out inner objects, then, in every object use another oner reduce to get tasks in that data-type what you need.您可以获取对象的键,并在遍历它们时找出内部对象,然后在每个 object 中使用另一个 reduce 来获取您需要的数据类型的任务。 for iterations i suddenly use reduce() method as a swiss-knife to working with arrays.
对于迭代,我突然使用 reduce() 方法作为使用 arrays 的瑞士刀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.