简体   繁体   English

从 API Javascript 内的嵌套数据结构中检索多个值

[英]Retrieve multiple values from nested data structures within API Javascript

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.以下是来自 rapid.api 的 NBA API 响应。此特定响应( https://api-nba-v1.p.rapidapi.com/games/live/ )现在正在直播 NBA。

I'm using this API and various responses in other, straightforward ways to retrieve NBA information.我正在使用这个 API 和其他直接的方式来检索 NBA 信息的各种响应。 My script is designed for Discord.我的脚本是为 Discord 设计的。

In this Discord Server I have, we make channels for every NBA game so that users can chat about it.在我拥有的这个 Discord 服务器中,我们为每场 NBA 比赛制作频道,以便用户可以聊天。 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;我一直在努力寻找一种方法;

  1. Match the channel name via the nickName of a team (an example of a game channel name would be: lakers-vs-nets), which will allow me to make sure that I get the score for the correct game通过球队的昵称匹配频道名称(比赛频道名称的示例是:lakers-vs-nets),这将允许我确保获得正确比赛的分数
  2. Retrieve the score from both the home and away teams检索主队和客队的比分
  3. Print the score from both the home and away teams.打印主队和客队的比分。

I'm unfamiliar with APIs and trying to get better with them, and I have learned more creative ways to use Javascript.我不熟悉 API 并试图更好地使用它们,并且我学会了更多创造性的方法来使用 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. vTeam 和 hTeam 在这里折叠以压缩代码,但它应该让您了解响应,因为它与之前的几乎相同,只是不同的团队、分数等。

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.你可以看到我发表了一些评论,这些评论只是为了帮助理解我以前的尝试,但我觉得其中一个可能只是在正确的边缘。

With the API Results listed above you could do something like,使用上面列出的 API 结果,您可以执行以下操作,

// 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 从频道名称中获取团队名称。

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

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

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