0

我有一个看起来像这样的对象数组:

const teams = [{
  name: 'Liverpool',
  won: true,
  opponent: 'Man Utd'
}, {
  name: 'Liverpool',
  won: true,
  opponent: 'Norwich'
}, {
  name: 'Chelsea',
  won: false,
  opponent: 'Arsenal'
},{
  name: 'Newcastle',
  won: true,
  opponent: 'Liverpool'
}];

我希望最终的数组如下所示。它应该只将一支球队添加到新数组中并计算球队赢了多少场比赛。顺序并不重要。

const transformedTeams = [{
    name: 'Liverpool',
    won: 2
  },
  {
    name: 'Newcastle',
    won: 1
  },
  {
    name: 'Chelsea',
    won: 0
  }
];

我写的代码看起来像这样,但不幸的是没有返回正确的值:

teams.map(team => {
  if(teams.includes(team.name)) {
    return {
      name: team.name,
      won: team.won === true ? 1 : 0
    }
  }
})
4

4 回答 4

2

方法

您可以存储具有团队名称键值和获胜比赛数的对象

const teamWonMapping = teams.reduce((acc, team) => {
  acc[team.name] = (acc[team.name] || 0) + (team.won ? 1 : 0)
  return acc
}, {})

const res = Object.entries(teamWonMapping).map(([name, won]) => ({ name, won }))

完整代码

const teams = [
  {
    name: "Liverpool",
    won: true,
    opponent: "Man Utd",
  },
  {
    name: "Liverpool",
    won: true,
    opponent: "Liverpool",
  },
  {
    name: "Chelsea",
    won: false,
    opponent: "Arsenal",
  },
  {
    name: "Newcastle",
    won: true,
    opponent: "Liverpool",
  },
]

const teamWonMapping = teams.reduce((acc, team) => {
  acc[team.name] = (acc[team.name] || 0) + (team.won ? 1 : 0)
  return acc
}, {})

const res = Object.entries(teamWonMapping).map(([name, won]) => ({ name, won }))

console.log(res)


参考

Array.prototype.reduce()

对象条目()

于 2020-08-25T14:02:37.223 回答
1

我会遍历数组,形成一个对象,形式如下:

{
  [team]: [number of wins]
}

然后我将转换最终数组中的对象。所以

const mapping = {}
teams.forEach(team => {
  if (mapping[team.name] === undefined) {
    mapping[team.name] = 0
  }
  mapping[team.name] += team.won ? 1 : 0
})

const result = Object.entries(mapping).map(([name, won]) => {
  return { name, won }
})
于 2020-08-25T14:03:38.453 回答
0

您可以创建一个由团队键入的临时计数器对象,进行计数,然后将其转换为您想要的结构。

这是如何工作的:

const teams = [{ name: 'Liverpool', won: true,opponent: 'Man Utd'}, {name: 'Liverpool',won: true,opponent: 'Norwich'}, {name: 'Chelsea',won: false,opponent: 'Arsenal'},{name: 'Newcastle',won: true,opponent: 'Liverpool'}];

let counter = Object.fromEntries(teams.map(({name}) => [name, 0]));
for (let {name, won} of teams) counter[name] += won;
let result = Object.entries(counter).map(([name, won]) => ({ name, won }));

console.log(result);

于 2020-08-25T14:10:49.727 回答
0

每次在返回块中运行代码时,您都将“赢得”值设置为 1,而不是递增它。您的 if 语句应该查看“赢得”值是否大于 0。如果它不是使用“++”递增,则将其设置为 1。

于 2020-08-25T14:06:32.740 回答