私はこのような配列を持っています:
const teamsPoints = [
{team1_game00: 1},
{team1_game01: 2},
{team1_game02: 3},
{team2_game00: 0},
{team2_game10: 2},
{team2_game11: 3},
{team3_game01: 0},
{team3_game10: 0},
{team3_game20: 3},
{team4_game02: 0},
{team4_game11: 0},
{team4_game20: 0}
]
私が取得しようとしているのは:
{
team1: 6,
team2: 5,
team3: 3,
team4: 0
}
これは、すべてのチームのポイントの合計です。
私はreduceメソッドを使用してそれを達成しようとしていました。
const scoreResult = teamsPoints.reduce((total, current) => {
}, {});
私は空のオブジェクトから始めていることを理解していますが、適切なキーと値のペアを取得するのに問題があります(そのため、ここでは公開していません。adminreduceメソッドは私にとってちょっと新しいことです)。
前もって感謝します!
これは、を使用した小さなサンプルreduce
です。私は基本的にチームの名前を取得し、それを縮小結果のキーとして使用し、その値をインクリメントします!
これがお役に立てば幸いです;)不明な点がある場合は、遠慮なく質問してください。
const teamsPoints = [
{team1_game00: 1},
{team1_game01: 2},
{team1_game02: 3},
{team2_game00: 0},
{team2_game10: 2},
{team2_game11: 3},
{team3_game01: 0},
{team3_game10: 0},
{team3_game20: 3},
{team4_game02: 0},
{team4_game11: 0},
{team4_game20: 0}
];
const scoreResult = teamsPoints.reduce((total, game) => {
const [gameName] = Object.keys(game);
const [team] = gameName.split('_');
total[team] = total[team] || 0;
total[team] += game[gameName];
return total;
}, {});
console.log(scoreResult);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加