如何分组和JavaScript对象的总和数组?

时间:2020-08-07 07:03:06

标签: javascript

在我使用reduce()将对象按月-年分组到数组中之后:

let groupByMonth;
if (newlistTaskEvaluation) {
    groupDataByMonth = newlistTaskEvaluation.reduce((groups, item) => {
     groups[item.time] = [...groups[item.time] || [], item];
      return groups;
     }, {});
}

我有一组按月/年分组的事件对象,如下所示:

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 },
            ]
        },
    ]
}

如何按键“代码”,时间和总和按值分组数组对象?

预期结果:

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
        ]
    }
]

请帮助我。

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情

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 }))
  }
}

一个缺点是,由于数据结构的原因,时间复杂度并不理想

答案 1 :(得分:2)

    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))

您可以获取对象的键,并在对其进行迭代时查找内部对象,然后,在每个对象中使用另一个oner reduce来获得所需的该数据类型的任务。 对于迭代,我突然将reduce()方法用作处理数组的瑞士刀。