Reputation: 7
I reformatted this question to correctly display the issue and show my previous attempts to get my desired results.
Below is an NBA API response from rapid.api This specific response (https://api-nba-v1.p.rapidapi.com/games/live/) spits out the current NBA Games that are live/ongoing right now.
I'm using this API and various responses in other, straightforward ways to retrieve NBA information. My script is designed for Discord.
In this Discord Server I have, we make channels for every NBA game so that users can chat about it. I have been trying to make a score command showing the current game score.
My issue/goal:
I've been struggling to find a way to;
I'm unfamiliar with APIs and trying to get better with them, and I have learned more creative ways to use Javascript. So any help and explanations with this issue would be greatly appreciated; thank you.
"api":{
"status":200
"message":"GET games/live"
"results":4
"filters":[
0:"seasonYear"
1:"league"
2:"gameId"
3:"teamId"
4:"date"
5:"live"
]
"games": [
0: {
"seasonYear":"2021"
"league":"standard"
"gameId":"10187"
"startTimeUTC":"2022-01-13T00:30:00.000Z"
"endTimeUTC":""
"arena":"Madison Square Garden"
"city":"New York"
"country":"USA"
"clock":"1:35"
"gameDuration":"2:05"
"currentPeriod":"4/4"
"halftime":"0"
"EndOfPeriod":"0"
"seasonStage":"2"
"statusShortGame":"2"
"statusGame":"In Play"
"vTeam":{
"teamId":"8"
"shortName":"DAL"
"fullName":"Dallas Mavericks"
"nickName":"Mavericks"
"logo":"https://upload.wikimedia.org/wikipedia/fr/thumb/b/b8/Mavericks_de_Dallas_logo.svg/150px-Mavericks_de_Dallas_logo.svg.png"
"score": {
"points":"82"
}
}
"hTeam":{
"teamId":"24"
"shortName":"NYK"
"fullName":"New York Knicks"
"nickName":"Knicks"
"logo":"https://upload.wikimedia.org/wikipedia/fr/d/dc/NY_Knicks_Logo_2011.png"
"score":{
"points":"121"
}
}
1: {
"seasonYear":"2021"
"league":"standard"
"gameId":"10189"
"startTimeUTC":"2022-01-13T02:00:00.000Z"
"endTimeUTC":""
"arena":"Vivint Arena"
"city":"Salt Lake City"
"country":"USA"
"clock":"8:08"
"gameDuration":"1:46"
"currentPeriod":"4/4"
"halftime":"0"
"EndOfPeriod":"0"
"seasonStage":"2"
"statusShortGame":"2"
"statusGame":"In Play"
"vTeam":{...}
"hTeam":{...}
]
}
}
vTeam and hTeam are collapsed here to condense the code but it should give you an idea of the response, as it is nearly identical to the one prior, just different teams, score etc.
Here's some code I have tried so far:
function iterationObject(obj) {
for(prop in obj) {
// If Object
if (typeof(obj[prop]) == "object"){
// Push
iterationObject(obj[prop]);
} else {
/* This only seems to work if I run solely search for the keys and not the values. So for example, this would work:
if (prop == "nickName" || prop == "shortName"){
console.log(prop + ': ', obj[prop])
}
^ This would work and print the values from anything matching nickName and shortName keys (so in this case, it would print every nickName and shortName it found.*/
if (prop == "nickName" && obj[prop] == "Knicks"){
console.log(prop + ': ', obj[prop])
// ^ This is the last thing that I have tried, but has been returning undefined.
}
}
}
}
case 'gamescore':
var gamescoreurl = "https://api-nba-v1.p.rapidapi.com/games/live/";
axios.get(gamescoreurl, {
headers: {
"x-rapidapi-key": apikey,
"x-rapidapi-host": apihost
}
}).then(response=> {
/* Something I tried with .find, only seems to search surface level with the response. What I mean by that is,
I can dive into games API response, but I can't go games.hTeam with .find
var firstchannelpart = message.channel.name
var gamechannelfinder = firstchannelpart.split("-")[0];
var gameapiresp= response.data.api.games
const hscore = gameapiresp.find(el => {
return el.nickName== gamechannelfinder
})
console.log(hscore)
*/
// My latest attempt, which works retrieving specific values that match using prop as a var in iterationObject. Also, the item variable returns as undefined here, but iterationObject will print from the console what it is supposed to.
tidobj.filter(item => {
iterationObject(item)
})})
break;
You can see I put in some comments, those are solely for this thread to help understand my previous attempts, but I feel that one of them might be just on the brink of being right.
Upvotes: 0
Views: 141
Reputation: 16
With the API Results listed above you could do something like,
// Set up our sample vars
let channelName = "Mavericks-vs-Knicks";
let gamescoreurl = "https://api-nba-v1.p.rapidapi.com/games/live/";
// Make Axios Call
axios.get(gamescoreurl, {
headers: {
"x-rapidapi-key": apikey,
"x-rapidapi-host": apihost
}
}).then(results => {
// get array of team names to pass to 'LogGameScores'
let teamNickNames = GetTeamsFromChannelName(channelName);
// Log the game scores
LogGameScores(teamNickNames, results?.games);
})
This is a simple function to get the team names from the channel name.
function GetTeamsFromChannelName(name = "channelName") {
return name.split("-vs-"); // Split the team Nick Names from the channel name
}
And the a method for getting / logging the scores
function LogGameScores(teams = [], games = null) {
// verify params and log errors found
if (games == null)
return console.log("An error occured while trying to log games scores");
if (teams.length < 2)
return console.log("An error occured while trying to log games scores");
try {
// filter the results to just the game or games representing the teams
// we want from the returned results
let game = games.filter((el) => {
return (
// Check for the game that matches both teams. You are likely able
// to match by only one team name but just in case
// Check for the teams name in the visiting team section
(el.vTeam.nickName.toLowerCase() == teams[0].toLowerCase()
|| el.vTeam.nickName.toLowerCase() == teams[1].toLowerCase())
// Check for the teams name in the home teams section
&& (el.hTeam.nickName.toLowerCase() == teams[0].toLowerCase()
|| el.hTeam.nickName.toLowerCase() == teams[1].toLowerCase())
);
});
// log the scores for the home team and visiting team to the console
game.forEach((el) => {
console.log(`(Home) ${el.hTeam.nickName}: ${el.hTeam.score.points}`);
console.log(`(Visitor) ${el.vTeam.nickName}: ${el.vTeam.score.points}`);
});
} catch (error) {
console.log({ error, teams, games});
}
}
Upvotes: 0