ES6处理对象(简化功能)

时间:2018-10-12 09:05:56

标签: javascript function object ecmascript-6

罗马尼亚的问候,

给出游戏列表,这些游戏看起来像:

  {
    "id": 112814,
    "matches": "123",
    "tries": "11"
  }

返回类似这样的对象

  {
    "totalMatches": m,
    "totalTries": y
  }

其中m是所有游戏的所有比赛的总和   t是所有游戏的所有尝试之和。

 input = [
    {"id": 1,"matches": "123","tries": "11"},
    {"id": 2,"matches": "1","tries": "1"},
    {"id": 3,"matches": "2","tries": "5"}
  ]

  output = {
    matches: 126,
    tries: 17
  }

我目前拥有的东西:

function countStats(list) {


  return {
    matches: 0,
    tries: 0
  };
}

我认为我需要做的事情:

  1. 遍历所有对象
  2. 使用全局变量计算匹配数(m)并尝试(y)
  3. 分别返回m,y

我被告知要做的事情,我不知道该怎么做:  1.使用减少功能  2.改为返回一个对象

非常感谢您的任何建议

5 个答案:

答案 0 :(得分:2)

您可以使用Array.reduce

const input = [
  {"id": 1, "matches": "123", "tries": "11"},
  {"id": 2, "matches": "1", "tries": "1"},
  {"id": 3, "matches": "2", "tries": "5"}
];
  
const result = input.reduce((result, entry) => {
  result.matches += +entry.matches;
  result.tries += +entry.tries;
  return result;
}, {matches: 0, tries: 0});

console.log(result);

答案 1 :(得分:1)

您应在诸如此类的字段上使用reduce

function countStats (list) {
  return {
    matches: input.reduce((a, b) => +a + +b.matches, 0),
    tries: input.reduce((a, b) => +a + +b.tries, 0)
  }
}

请参见语法糖,以将字符串作为数字求和,即+a + +b

答案 2 :(得分:0)

您可以将结果取值为0的对象,并获取以后用于迭代数组的键和添加相同键值的键。

var input = [{ id: 1, matches: "123", tries: "11" }, { id: 2, matches: "1", tries: "1" }, { id: 3, matches: "2", tries: "5" }],
    output = { matches: 0, tries: 0 },
    keys = Object.keys(output);

input.forEach(o => keys.forEach(k => output[k] += +o[k]));

console.log(output);

答案 3 :(得分:0)

这是一种干净的方法:

const games = [
  { id: 1, matches: '123', tries: '11' },
  { id: 2, matches: '1', tries: '1' },
  { id: 3, matches: '2', tries: '5' },
];

const reduced = games.reduce(
  (accumulator, game) => ({
    totalMatches: accumulator.totalMatches + Number(game.matches),
    totalTries: accumulator.totalTries + Number(game.tries),
  }),
  { totalMatches: 0, totalTries: 0 }
);

console.log(reduced);

答案 4 :(得分:0)

input = [
  {"id": 1,"matches": "123","tries": "11"},
  {"id": 2,"matches": "1","tries": "1"},
  {"id": 3,"matches": "2","tries": "5"}
]

let totalMatches = 0;
let totalTries = 0;
let output = input.reduce(({totalMatches, totalTries}, {matches, tries}) => {
  totalMatches += +matches;
  totalTries += +tries;
  return {totalMatches, totalTries}
},{totalMatches: 0, totalTries: 0});

console.log(output)