下面的示例获取与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"}
答案 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))