【问题标题】:Count same property value from multiple objects计算来自多个对象的相同属性值
【发布时间】:2022-01-20 11:30:09
【问题描述】:

我正在编写 Football Team Builder 代码,并希望从多个对象中计算特定属性。在这种情况下,我想统计 5 个足球运动员的国籍。 需要计算来自同一国家的足球运动员的数量,并将其添加到现役球员的技能点总数中。 (见代码)

我在这里阅读了一些关于“Object.keys”的内容,但我对 JavaScript 的了解似乎太低,无法正确使用它。

HTML

<h1> Create your Five-a-side Team </h1>
<p> Formation: <span>1-2-1</span></p>

<p>
Attacker 1: <span id="attacker_1">  </span> <br>
Midfielder 1: <span id="midfielder_1"> </span> <br>
Midfielder 2: <span id="midfielder_2"> </span> <br>
Defender 1: <span id="defender_1"> </span> <br>
Keeper: <span id="keeper"> </span> <br>
</p>

<p>
Total Skill Points: <span id="total_skill_points"> 0</span>&#9733;
</p>

<p>
You have <span id="same_nation_count">0</span>  
players from <span id="nation_name">the same Nation</span>. 
<br>
That means you got <span id="bonus_points"
>0</span> Bonus points added to your Total Skill Points!
</p>

JavaScript

// Attacker 1
const captain_01 = {
    firstName: 'Johan', 
  lastName: 'Cruijff',
  skillPoints: 5,
  position: 'Attacker',
  club: 'FC Barcelona',
  nation: 'The Netherlands'
}; captain_01.fullName = `${captain_01.firstName} ${captain_01.lastName}`;

// Midfielder 1
const topclass_01 = {
    firstName: 'Frenkie', 
  lastName: 'de Jong',
  skillPoints: 4,
  position: 'Midfielder',
  club: 'FC Barcelona',
  nation: 'The Netherlands'
}; topclass_01.fullName = `${topclass_01.firstName} 
${topclass_01.lastName}`;

// Midfielder 2
const talent_01 = {
    firstName: 'Ryan',
  lastName: 'Gravenberch',
  skillPoints: 3,
  position: 'Midfielder',
  club: 'Ajax',
  nation: 'The Netherlands'
}; talent_01.fullName = `${talent_01.firstName} 
${talent_01.lastName}`;

// Defender 1
const worldclass_01 = {
    firstName: 'Virgil', 
  lastName: 'van Dijk',
  skillPoints: 5,
  position: 'Defender',
  club: 'Liverpool',
  nation: 'The Netherlands'
}; worldclass_01.fullName = `${worldclass_01.firstName} 
${worldclass_01.lastName}`;

// Keeper 
const keeper_01 = {
    firstName: 'Gianluigi',
  lastName: 'Donnarumma',
  skillPoints: 5,
  position: 'Keeper',
  club: 'PSG',
  nation: 'Italy'
}; keeper_01.fullName = `${keeper_01.firstName} 
${keeper_01.lastName}`;


// Active Attacker 1
document.getElementById("attacker_1").innerHTML =
`${captain_01.fullName} (${captain_01.skillPoints}&#9733;) 
(${captain_01.nation})`;

// Active Midfielder 1
document.getElementById("midfielder_1").innerHTML =
`${talent_01.fullName} (${talent_01.skillPoints}&#9733;)
(${talent_01.nation})`;

// Active Midfielder 2
document.getElementById("midfielder_2").innerHTML =
`${topclass_01.fullName} (${topclass_01.skillPoints}&#9733;)
(${topclass_01.nation})`;

// Active Defender 1
document.getElementById("defender_1").innerHTML =
`${worldclass_01.fullName} (${worldclass_01.skillPoints}&#9733;) (${worldclass_01.nation})`;

// Active Keeper
document.getElementById("keeper").innerHTML =
`${keeper_01.fullName} (${keeper_01.skillPoints}&#9733;)
(${keeper_01.nation})`;


// Counts the amount of players from the same nation
let nationCount = '';

// Counts Bonus Points to the Total Skill Points
let bonusPoints = nationCount;
document.getElementById("bonus_points").innerHTML =
bonusPoints;

// Total Skill Points calculator
document.getElementById("total_skill_points").innerHTML =
captain_01.skillPoints + talent_01.skillPoints + 
topclass_01.skillPoints + worldclass_01.skillPoints + 
keeper_01.skillPoints + bonusPoints;

// Sets name for nation by calculating the most common nation among the players
document.getElementById("nation_name").innerHTML ;

这是我的 JSFiddle:https://jsfiddle.net/u3tL65xz/1/

【问题讨论】:

  • 澄清一下,您想计算代表的每个国家吗?您的代码似乎不支持这一点。只有一个 nationCount 变量可以增加奖励积分。您的玩家列表中有两个国家。你能澄清一下吗?
  • 是的!每个国家都需要被计算在内。这个想法是,当有 2 个或更多来自同一国家的玩家时,每个玩家都会增加 1 个额外的奖励积分。因此,在这种情况下,不应计算 1 名来自意大利的球员。
  • 好的,看我的回答。在第二个解决方案(withNation)中,您拥有每个国家和计数。我会让你应用积分计算的逻辑。
  • 因为你想要国家,我已经编辑了我的答案,所以只有一个解决方案,包括国家和删除的解决方案,只有每个解决方案的计数。如果你想要回来,请告诉我。

标签: javascript object properties


【解决方案1】:

首先将播放器对象放入一个集合中,以便于处理它们。然后从玩家列表中创建一个唯一的“国家”列表。您可以通过使用 Set 对象来确保唯一性。然后,您可以简单地根据 nation 属性在字段上进行过滤,并计算所代表的每个唯一国家的总数。

const captain_01={firstName:'Johan',lastName:'Cruijff',skillPoints:5,position:'Attacker',club:'FC Barcelona',nation:'The Netherlands'};captain_01.fullName=`${captain_01.firstName} ${captain_01.lastName}`;const topclass_01={firstName:'Frenkie',lastName:'de Jong',skillPoints:4,position:'Midfielder',club:'FC Barcelona',nation:'The Netherlands'};topclass_01.fullName=`${topclass_01.firstName} 
${topclass_01.lastName}`;const talent_01={firstName:'Ryan',lastName:'Gravenberch',skillPoints:3,position:'Midfielder',club:'Ajax',nation:'The Netherlands'};const worldclass_01={firstName:'Virgil',lastName:'van Dijk',skillPoints:5,position:'Defender',club:'Liverpool',nation:'The Netherlands'};const keeper_01={firstName:'Gianluigi',lastName:'Donnarumma',skillPoints:5,position:'Keeper',club:'PSG',nation:'Italy'};

const players = [captain_01, topclass_01, talent_01, worldclass_01,keeper_01];
const nations = new Set(players.map(p=>p.nation));
const output = Array.from(nations).map(n=>{return {[n]:players.filter(p=>p.nation === n).length}});

console.log(output);

【讨论】:

    【解决方案2】:

    由于您已准备好 5 个玩家的对象,因此计算按国家/地区分组的玩家数量非常简单。下面是sn-p,它显示了将所有5个玩家的对象收集到一个数组中,并使用循环遍历玩家的对象,最后将它们存储在nationCount中。如果国家第一次进入循环,当我们尝试find 时,nationCount 中将没有数据,所以我们推送计数为 1 的对象。如果同一个国家第二次或更多次进入循环超过两倍,我们只是增加了count 的值。所以最后nationCount 的结果会是这样的:

    [
        {
             nation: "The Netherlands",
             count: 5
        },
        ... and so on for more countries
    ]
    

    let players = [{ firstName: 'Johan', lastName: 'Cruijff', skillPoints: 5, position: 'Attacker', club: 'FC Barcelona', nation: 'The Netherlands' },{ firstName: 'Virgil', lastName: 'van Dijk', skillPoints: 5, position: 'Defender', club: 'Liverpool', nation: 'The Netherlands' },{ firstName: 'Frenkie', lastName: 'de Jong', skillPoints: 4, position: 'Midfielder', club: 'FC Barcelona', nation: 'The Netherlands' },{ firstName: 'Ryan', lastName: 'Gravenberch', skillPoints: 3, position: 'Midfielder', club: 'Ajax', nation: 'The Netherlands' },{ firstName: 'Jasper', lastName: 'Cillessen', skillPoints: 2, position: 'Keeper', club: 'Valencia', nation: 'India' }]
    
    // In your case, ignore the above one. The players object should be the one below.
    //let players = [captain_01,talent_01,topclass_01,talent_01,average_01];
    let nationCount = [];
    for (let player of players) {
      let existingNation = nationCount.find(ele => ele.nation === player.nation)
      if (existingNation)
        existingNation.count++;
      else
        nationCount.push({
          nation: player.nation,
          count: 1
        })
    }
    console.log(nationCount)

    我希望这个对象能帮助你进一步处理你的游戏逻辑来操作点数。

    【讨论】:

      【解决方案3】:

      一个简单的解决方案是遍历对象并计算nation的出现次数

      async function nationPlayerMapper() { 
          const arr = {};
          const data = [captain_01,worldclass_01,average_01,topclass_01,talent_01];
          await data.map(obj => {
              const {nation} = obj;
              if (!arr[nation]) {
                  arr[nation] = 1;
              } else {
                  arr[nation] += 1;
          }
          });
        
        for (let [nation, count] of Object.entries(arr)) {
          console.log(`Count Of Same Players From ${nation} is ${count}`);
        }
       
      }
      
      // Counts the amount of players from the same Nation
      let nationCount = nationPlayerMapper();
      

      let captain_01 = {
          firstName: 'Johan', 
        lastName: 'Cruijff',
        skillPoints: 5,
        position: 'Attacker',
        club: 'FC Barcelona',
        nation: 'The Netherlands'
      };
      captain_01.fullName = `${captain_01.firstName} ${captain_01.lastName}`;
      
      let worldclass_01 = {
          firstName: 'Virgil', 
        lastName: 'van Dijk',
        skillPoints: 5,
        position: 'Defender',
        club: 'Liverpool',
        nation: 'The Netherlands'
      };
      worldclass_01.fullName = `${worldclass_01.firstName} 
      ${worldclass_01.lastName}`;
      
      let topclass_01 = {
          firstName: 'Frenkie', 
        lastName: 'de Jong',
        skillPoints: 4,
        position: 'Midfielder',
        club: 'FC Barcelona',
        nation: 'The Netherlands'
      };
      topclass_01.fullName = `${topclass_01.firstName} 
      ${topclass_01.lastName}`;
      
      let talent_01 = {
          firstName: 'Ryan',
        lastName: 'Gravenberch',
        skillPoints: 3,
        position: 'Midfielder',
        club: 'Ajax',
        nation: 'The Netherlands'
      };
      talent_01.fullName = `${talent_01.firstName} 
      ${talent_01.lastName}`;
      
      let average_01 = {
          firstName: 'Jasper',
        lastName: 'Cillessen',
        skillPoints: 2,
        position: 'Keeper',
        club: 'Valencia',
        nation: 'The Netherlands'
      };
      
      async function nationPlayerMapper() { 
          const arr = {};
          const data = [captain_01,worldclass_01,average_01,topclass_01,talent_01];
          await data.map(obj => {
              const {nation} = obj;
              if (!arr[nation]) {
                  arr[nation] = 1;
              } else {
                  arr[nation] += 1;
          }
          });
        
        for (let [nation, count] of Object.entries(arr)) {
          console.log(`Count Of Same Players From ${nation} is ${count}`);
        }
       
      }
      
      // Counts the amount of players from the same Nation
      let nationCount = nationPlayerMapper();

      【讨论】:

      • 这段代码中不需要async/await - 根本没有异步操作。
      猜你喜欢
      • 2022-07-03
      • 2015-06-30
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多