问题描述
我正在创建一个google chrome扩展程序,它将使用存储在JSON
文件中的某些数据.我需要组成一个由11个成员组成的团队,这些团队需要从已处理的JSON
文件中提取出来,但是我不知道如何进行.解析完文件后,我希望每个团队位置只有x个团队成员.例如,我需要随机选择一名守门员,三名,四名或五名后卫,三名四或五名中场和一,二或三名攻击者.使用PHP
,我可以毫无问题地做到这一点,但是我对javascript没有太多的经验,我需要帮助.有什么功能或方法可以实现吗?
I'm creating a google chrome extension that will use some data that are stored inside a JSON
file. I need to compose a team of 11 members that needs to be extracted from the processed JSON
file, but I don't know how to proceed. After I've parsed the file, I want that for every team position there are only x team members. For example, I need to randomly select one Goalkeeper, three, four or five defenders, three four or five midfield and one, two or three attackers. With PHP
I'm able to do that without problems, but I'm not very experienced with javascript and I need help. Is there any function or any way to achieve this?
{
"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
});
推荐答案
可以使用reduce
,map
和filter
的组合来组建团队:
A combination of reduce
, map
and filter
can be used to setup teams:
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)
查看演示
这篇关于使用javascript从数组中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!