gpt4 book ai didi

javascript - 将对象数组添加到一起

转载 作者:行者123 更新时间:2023-11-28 17:16:04 26 4
gpt4 key购买 nike

我正在尝试使用reduce 将对象数组添加在一起,但我无法让它工作。

const testArray = [ 
{
"T1": 1
},
{
"T2": 12
},
{
"T3": 20
}
]

归约函数

const q = testArray.reduce((count, x) => count + x.P1Count);

结果 = 33

最佳答案

您也可以获取值并减少值。

const
add = (a, b) => a + b,
array = [{ "T1": 1 }, { "T2": 12 }, { "T3": 20 }],
total = array.reduce(
(s, o) => Object.values(o).reduce(add, s),
0
);

console.log(total);

关于javascript - 将对象数组添加到一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com