Skip to content
Advertisement

Match key/values in JSON object

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.

JavaScript

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

JavaScript

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

JavaScript

It would say

JavaScript

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.

Advertisement

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:

JavaScript

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

Advertisement