Match key/values in JSON object

Tags: , , ,



I have a school project where we are learning JSON. What I am trying to do is figure out how I can match keys with other keys that exist in another object property.

I’m using an old api to pull nfl player information. Here is an example of the url to pull the data:

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

I’m using AJAX to call the data and stringify the results into a table.

  $.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);

});

Here is a fiddle of what I am doing: https://jsfiddle.net/kenneth2k1/kcf5duLr/

If you notice the results, I have the stats property separated out in its own column, but it is still in the object’s key/value structure.

Now, here is another url that has what each stat is: 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

So for example key ID “1” corresponds with “Games Played” from the stat reference object.

I am new to all this, so what I can’t wrap my head around is if I wanted to sub out the keys in my output with the corresponding name value from the stats reference object, how would I do that?

For example from the jsfiddle output, Instead of

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

It would say

Games Played: 9, Rushing Attempts: 1

I hope that makes sense. Basically I’d like to learn how to match keys in one JSON object with the key values in another.

Thank you very much for assistance.

Answer

You could nest your second AJAX call in the success function of your first call, then put your variable assignments and table creation into the second success function. Inside the second success function you’d use simple for loops to match each numerical statistic from the player data with the correct name of the statistic in the statistics data, like this:

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

      });

    }
  });
});

You’ll probably want to do further text formatting on the output of prettyStats, but it gets you the data you’re looking for.



Source: stackoverflow