计算某个值在javascript中出现的时间

时间:2019-09-09 09:45:29

标签: javascript string object

我有一个api响应,已将其解析为如下所示的Javascript对象:

teams [{
    0:
    1:
    2:
    3:
    4:
    5:
}]

100个数字中的每一个都包含以下信息:

teams [{
    0:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 5
      winning_id: 54
    1:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 5
      winning_id: 24
    2:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 3
      winning_id: 54
    3:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 2
      winning_id: 27
    4:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 4
      winning_id: 75
    5:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 6
      winning_id: 27
}]

我需要使用winning_id查找并计算每个不同的团队赢得了多少次。谁能帮忙。

我尝试将所有winning_ids合并到一个数组中,以便我可以计数,但那没有用,我还尝试过将它们转换为字符串以这种方式计数,但也没有用。

结果应该是每个ID的计数,例如:

54:2

24:1

27:2

75:1

1 个答案:

答案 0 :(得分:0)

const teams = [{
    0: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 5, winning_id: 54,},
    1: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 5, winning_id: 24,},
    2: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 3, winning_id: 54,},
    3: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 2, winning_id: 27,},
    4: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 4, winning_id: 75,},
    5: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 6, winning_id: 27,},
}];

const response = Object.values(teams[0]).reduce(
  (res, {winning_id}) => ({
    ...res, 
    [winning_id]: (res[winning_id] || 0) + 1
  }),
{});
console.log(response);

您可以尝试Array.reduce()并在winning_id出现时累积