gpt4 book ai didi

javascript - 如何使用Array.reduce()?

转载 作者:行者123 更新时间:2023-11-28 17:30:47 25 4
gpt4 key购买 nike

我有一个如下所示的 JSON 响应:

[
{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}],
]

如何对每个数据元素内的每个“值”(按列)求和并得到如下结果:

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

如何使用 array.reduce() 来实现此目的,或者是否有其他方法可以实现上述结果?

最佳答案

尝试以下逻辑。

var series = [{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]}, ... , ....]

var resultSeries = series.reduce((acc, cur) => {
var result = {
name: ‘Something’,
data: []
};
var dataArray = acc.data.map((el, i) => {
var curData = cur.data[i] || {};
var sum = (el.value || 0) + (curData.value || 0);
return {
value: sum
}
});
result.data = dataArray ;
return result;
})

现在resultSeries将保持

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

关于javascript - 如何使用Array.reduce()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508051/

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