简体   繁体   中英

extract data from array with 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?

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
});

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) 

Checkout the demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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