下面的示例,获取与 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"}
最佳答案
您可以仅使用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))
关于javascript - 有没有办法对这个对象数组进行分组或减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60077405/