_.sum按数组中相同键的总和

时间:2018-07-20 10:37:52

标签: javascript lodash

我正在努力在对象数组中获得相同键的所有值的输出。输出仅仅是总和(加法)。我用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

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:3)

使用_.values()(或本机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>