简体   繁体   中英

Return Array Instead of String

I am trying to get an array response from my getTeam() function so I can properly filter my DataTable to show more than one team for the current Player (if they are on more than one team).

DataTables Filter:

 $.fn.dataTable.ext.search.push( //creating my own filter function for the table function(settings, searchData, index, rowData, counter, statusClass) { var userName = searchData[1]; //created a var to search through the 3rd column (0 index) which contains all of the Monday Dates var searchTeam = searchData[0]; // Get Datatables API var api = $.fn.dataTable.Api('#myTable'); if (settings.sTableId === 'myTable' ) { if(userName === thisUserTitle){ return true; } else { return false; } } if (settings.sTableId === 'certificateTable' ) { if(currentTeam === searchTeam){ return true; } else { return false; } } return true; } );

The original snippet that returns just the first team:

 var teamData = [{ "Team": "Team 1", "Players":[ "Beerus Dev", "Goten Dev", "Trunks Dev", "Majin Bu Dev" ] }, { "Team": "Team 2", "Players": [ "Beerus Dev", "Shap Dev", "Krillin Dev" ] } ]; function getTeam() { const team = teamData.find(team => team.Players.includes(currentUser)); return team.Team; } var currentUser = "Beerus Dev"; var currentTeam = getTeam(currentUser); console.log(currentTeam);

To get the array response, I have tried using the .filter() as opposed to the .find() but I end up getting an empty array as my response.

 var teamData = [{ "Team": "Team 1", "Players":[ "Beerus Dev", "Goten Dev", "Trunks Dev", "Majin Bu Dev" ] }, { "Team": "Team 2", "Players": [ "Beerus Dev", "Shap Dev", "Krillin Dev" ] } ]; var currentUser = "Beerus Dev"; const team = teamData.filter(function(team, i){ return teamData[i].Players.includes(currentUser); }) console.log(team)

Simplify this code:

 var teamData = [{ "Team": "Team 1", "Players":[ "Beerus Dev", "Goten Dev", "Trunks Dev", "Majin Bu Dev" ] }, { "Team": "Team 2", "Players": [ "Beerus Dev", "Shap Dev", "Krillin Dev" ] } ]; var currentUser = "Beerus Dev"; const team = teamData.filter(team => team.Players.includes(currentUser)).map(team => team.Team); console.log(team)

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