繁体   English   中英

使用javascript从数组中提取数据

[英]extract data from array with javascript

我正在创建一个google chrome扩展程序,它将使用存储在JSON文件中的一些数据。 我需要组成一个由11个成员组成的团队,该团队需要从已处理的JSON文件中提取出来,但是我不知道如何进行。 解析文件后,我希望每个团队职位只有x个团队成员。 例如,我需要随机选择一名守门员,三名,四名或五名后卫,三名四或五名中场和一,二或三名攻击者。 使用PHP可以毫无问题地做到这一点,但是我对javascript的经验不是很丰富,我需要帮助。 有什么功能或任何方法可以实现这一目标吗?

JSON格式

{
"player_id":3,
"player_surname":"Immobile",
"player_name":"Ciro",
"player_number":17,
"team_name":"Lazio",
"team_abbreviation":"LAZ",
"role_abbreviation":"A",
"role_name":"Attaccante",
"quotation":62,
}

JS

const uri = 'api/players_.json';
$.getJSON(uri, function(data){
 // code stuff here
});

reducemapfilter组合可用于设置团队:

  const players = [ { "player_id":3, "player_surname":"Immobile", "player_name":"Ciro", "player_number":17, "team_name":"Lazio", "team_abbreviation":"LAZ", "role_abbreviation":"A", "role_name":"Attaccante", "quotation":62, }, { "player_id":3, "player_surname":"Immobile", "player_name":"Ciro", "player_number":17, "team_name":"Lazio", "team_abbreviation":"BLAA", "role_abbreviation":"A", "role_name":"Attaccante", "quotation":62, } ]; const playersPerTeam = Object.values(players.reduce((acc, player) => { const teamKey = player.team_abbreviation; if(!acc.hasOwnProperty(teamKey)){ acc[teamKey] = []; } acc[teamKey].push(player); return acc; }, {})); const chosenSetupPerTeam = playersPerTeam.map(playersInTeam => { const playersNeededPerRole = { "Portiere": 1, // Keeper "Difensore": 4, // Defender "Centrocampista": 4, // midfielder "Aggressore": 2, // Attacker }; const playersPresentPerRole = {}; // Get a team to fulfil the requirements stated in playersNeededPerRole return playersInTeam.filter(player => { // Role does not exist, thus the player can't join the team if(!playersNeededPerRole.hasOwnProperty(player.role_name)){ return false; } // Set the default of players present per role to 0 if(!playersPresentPerRole.hasOwnProperty(player.role_name)){ playersPresentPerRole[player.role_name] = 0; } // Stop if all positions have been filled as specified in playersNeededPerRole if(playersPresentPerRole[player.role_name] === playersNeededPerRole[player.role_name]){ return false; } playersPresentPerRole[player.role_name]++; return true; }); }); console.log(chosenSetupPerTeam) 

签出演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM