有没有一种方法可以分组或减少对象的数组

时间:2020-02-05 13:55:50

标签: javascript arrays sorting javascript-objects

下面的示例获取与period_str键的相同值相对应的总数学值。

[
     {math: 40, period_str: "Period 1, 03 2019"},
     {math: 32, period_str: "Period 1, 03 2019"},
     {math: 44, period_str: "Period 1, 02 2020"},
]

预期产量

[
{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}
]

或 输出(仅对象)

{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}

1 个答案:

答案 0 :(得分:1)

您可以仅使用period_str作为唯一键:

const arr = [
 {math: 40, period_str: "Period 1, 03 2019"},
 {math: 32, period_str: "Period 1, 03 2019"},
 {math: 44, period_str: "Period 1, 02 2020"},
]

const out = arr.reduce((a, v) => {
  if(a[v.period_str]) {
    a[v.period_str].math += v.math
  } else {
    a[v.period_str] = v
  }
  return a
}, {})

console.log(Object.values(out))