为数组对象分配值,然后将该值乘以匹配对象的数量

时间:2018-06-27 13:48:33

标签: javascript arrays reactjs ecmascript-6 lodash

我通过为匹配的字符串分配值来操纵数组。我现在想将该字符串的计数乘以我分配的值。

这是我的数组输出:

0: {gameScore: "R", reportDate: "2018-05-09", value: 2}
1: {gameScore: "M", reportDate: "2018-01-09", value: 1}
2: {gameScore: "M+", reportDate: "2018-02-09", value: 1.5}
3: {gameScore: "M+", reportDate: "2018-01-09", value: 1.5}
4: {gameScore: "M+", reportDate: "2018-02-09", value: 1.5}

我为gameScore分配了一个值:

const SCORES = {
    'R': 2,
    'M': 1,
    'M+': 1.5,
}

我想获取匹配对象的总数,例如“ M +” = 3,然后将其乘以我设置的'M+': 1.5,的初始值,这样"M+"最终将为'4.5'

var calculation = _(observations)
          .filter(observation => {
            return (
                moment(observation.reportDate).year() == moment().subtract('years', 1).year() && moment(observation.reportDate).month() > moment().subtract('years', 1).month()) ||
              (moment(observation.reportDate).year() == moment().year() && moment(observation.reportDate).month() < moment().month());
          })
          .omitBy(x => x.gameScore === "NULL")
          .map(observation => ({ ...observation,
            value: SCORES[observation.gameScore]
          }))
          .value();

我假设我需要对值做一些事情:SCORES[observation.gameScore]以获取对象数量并在达到这一点之前进行乘法运算?

在这里摆弄其他已经在使用的计算https://jsfiddle.net/xdtk2gn6/

使用lodash和ES6-致谢:)

1 个答案:

答案 0 :(得分:1)

您可以为此使用Array#reduce

const data = [
{gameScore: "R", reportDate: "2018-05-09", value: 2},
{gameScore: "M", reportDate: "2018-01-09", value: 1},
{gameScore: "M+", reportDate: "2018-02-09", value: 1.5},
{gameScore: "M+", reportDate: "2018-01-09", value: 1.5},
{gameScore: "M+", reportDate: "2018-02-09", value: 1.5}
];

const SCORES = {
    'R': 2,
    'M': 1,
    'M+': 1.5,
};

let result = data.reduce((acc, curr) => {
  acc[curr.gameScore] = acc[curr.gameScore] || 0; //Init value to 0 if it doesn't exist
  acc[curr.gameScore] += curr.value*SCORES[curr.gameScore]; //Add the current value * SCORE
  return acc;
},{});
console.log(result);