匹配JSON对象中的键/值

时间:2018-12-27 07:09:47

标签: javascript jquery json ajax

我有一个学校项目,我们正在学习JSON。我想做的是弄清楚如何将键与另一个对象属性中存在的其他键进行匹配。

我正在使用旧的api提取nfl播放器信息。这是提取数据的网址示例:

http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2018&week=16&format=json

我正在使用AJAX调用数据并将结果字符串化为表格。

  $.ajax({
   url: queryURL,
   method: "GET"
   }).then(function(response) {
     var tbl = $("<table>");
     $(tbl).addClass("table");
    var objCount = JSON.stringify(response.players.length);

    $(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th> 
    <th>Player</th><th>Stat</th></tr></thead><tbody>");


    for (p = 1; p < 2; p++) {
      var id = response.players[p].id;
      var team = response.players[p].teamAbbr;
      var pos = response.players[p].position;
      var plyr = response.players[p].name;
      var stat = JSON.stringify(response.players[p].stats);
      var plyrStatsObjLen = 
        JSON.stringify(response.players[p].stats.length);
  console.log("statObjLength: " + plyrStatsObjLen);

       $.each(response.players[p].stats, function(key, value) {
         console.log(key + ": " + value);
  });

  $(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + stat + "</td>");

}
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);

});

以下是我正在做的事情: https://jsfiddle.net/kenneth2k1/kcf5duLr/

如果您注意到结果,则将stats属性分隔在其自己的列中,但仍在对象的键/值结构中。

现在,这是另一个具有每个统计信息的网址: https://api.fantasy.nfl.com/v1/game/stats?format=json

"stats": [
{
"id": 1,
"abbr": "GP",
"name": "Games Played",
"shortName": "GP"
},
{
"id": 2,
"abbr": "Att",
"name": "Passing Attempts",
"shortName": "Pass Att"
},
{
"id": 3,
"abbr": "Comp",
"name": "Passing Completions",
"shortName": "Pass Comp"
}, ... and so on

例如,键ID“ 1”对应于统计参考对象中的“玩过的游戏”。

我对这一切都是陌生的,所以我不能为所欲为的是,如果我想用统计参考对象中的相应名称值来细分输出中的键,我该怎么做?

例如来自jsfiddle输出,而不是

{"1":"9","13":"1"}

会说

Games Played: 9, Rushing Attempts: 1

我希望这是有道理的。基本上,我想学习如何将一个JSON对象中的键与另一个对象中的键值进行匹配。

非常感谢您的协助。

1 个答案:

答案 0 :(得分:1)

您可以将第二个AJAX调用嵌套在第一个调用的成功函数中,然后将变量分配和表创建放入第二个成功函数。在第二个成功函数中,您将使用简单的for循环将玩家数据中的每个数字统计信息与统计数据中的统计信息的正确名称进行匹配,如下所示:

$(document).ready(function () {

  var statType = "seasonStats";
  var season = "2018";
  var week = "15";

  var playersURL = "https://api.fantasy.nfl.com/v1/players/stats?format=json" + "&statType=" + statType + "&season=" + season + "&week=" + week;
  var statURL = "https://api.fantasy.nfl.com/v1/game/stats?format=json";

  // Now we get the stats
  $.ajax({
    url: statURL,
    method: "GET",
    success: function (response) {
      const stats = response.stats;

      // Then we get the players
      $.ajax({
        url: playersURL,
        method: "GET",
        success: function (response) {
          const players = response.players;

          // Now we do the rest of the logic

          // Here's our table creation and header
          var tbl = $("<table>");
          $(tbl).addClass("table");
          $(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th><th>Player</th><th>Stat</th></tr></thead><tbody>");

          // Here's where we create variables for each individual player
          for (p = 0; p < 1; p++) {
            let id = players[p].id;
            let team = players[p].teamAbbr;
            let pos = players[p].position;
            let plyr = players[p].name;
            // We create an empty object to hold the named statistics we're about to find
            let statistics = {};

            // Now we'll loop over the players and statistics to get names for all the stats
            playerStats = players[p].stats;
            for (playerStat in playerStats) {
              for (s = 0; s < stats.length; s++) {
                // if the player's statistic matches the id of the property from the stats object, we add that stat name and its total for that player as a property of the object we created above
                if (playerStat === JSON.stringify(stats[s].id)) {
                  let statName = stats[s].name;
                  let statCount = playerStats[playerStat];
                  statistics[statName] = statCount;
                }
              }
            };
            // Now we turn our statistics object into text that can actually go into our table
            let prettyStats = "";
            for (statistic in statistics) {
              prettyStats = prettyStats + `${statistic}: ${statistics[statistic]}
              `
            }

            // Now that we have data for the player, we add a row to our table
            $(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + prettyStats + "</td>");
          }

          //Here's the bottom of our table and its creation inside the div
          $(tbl).append("</tbody><br/><br/>");
          $("#statOutput").append(tbl);
        }

      });

    }
  });
});

您可能想对prettyStats的输出进行进一步的文本格式化,但是它将为您提供所需的数据。