gpt4 book ai didi

javascript - _.sumBy 跨数组相同键的总计

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

我正在努力获取对象中数组中相同键的所有值的输出。输出只是总和(加法)。使用 lodash 我尝试过 sumBy。

// Here is my data:(question - how do I reformat the data below
// into one array as I think that would help)
const competitions = {
0: {gameScore: "2", reportDate: "2018-05-09", oldvalue: 2},
1: {gameScore: "3", reportDate: "2018-01-09", oldvalue: 1},
2: {gameScore: "4", reportDate: "2018-02-09", oldvalue: 1.5},
3: {gameScore: "5", reportDate: "2018-01-09", oldvalue: 1.5},
4: {gameScore: "6", reportDate: "2018-02-09", oldvalue: 1.5}
};

// This is what I have tried:
const formatted_data = _(competitions)
.groupBy('oldvalue')
.map((v) => ({
newValue: _.sumBy(v, 'oldvalue')
}))
.value();

console.log(formatted_data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

结果如下:

formatted_data = {
0: {newValue: 2},
1: {newValue: 1},
2: {newValue: 1.5},
3: {newValue: 1.5},
4: {newValue: 1.5}
}

它将旧值重新映射到 newVale,但希望将一个结果全部加在一起。

最终我需要formatted_data = 7.5

任何帮助都会很棒。

最佳答案

使用 _.values() 转换为数组(或 native Object.values() ),然后使用 _.sumBy()

注意: competitions 应该是一个数组,因为它们无论如何都有数字键。

const competitions = {
0: {gameScore: "2", reportDate: "2018-05-09", oldvalue: 2},
1: {gameScore: "3", reportDate: "2018-01-09", oldvalue: 1},
2: {gameScore: "4", reportDate: "2018-02-09", oldvalue: 1.5},
3: {gameScore: "5", reportDate: "2018-01-09", oldvalue: 1.5},
4: {gameScore: "6", reportDate: "2018-02-09", oldvalue: 1.5}
}

const result = _.sumBy(_.values(competitions), 'oldvalue');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

关于javascript - _.sumBy 跨数组相同键的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440685/

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