I have recently been learning javascript and wanted to just mess around with an API to try to learn about JSON. I watched some videos and it seemed simple. In the videos, they accessed properties using dot access. I am using the balldontlie.io API and my goal is just to display each player first name in the console. This is my code.
async function nba(){
const url = "https://www.balldontlie.io/api/v1/players";
const response = fetch(url);
const data = (await response).json();
console.log(data);
}
nba();
When I look in my console, it seems that there is a result object that has a "meta" and a "data". The values that I want to loop over and print are in the data but I do not know how to access them. I have tried to do dot access like I saw in other videos but clearly it is not working so far. Thanks for your help.
2
Answers
Following code will work for you:
Let’s understand the above code. Fetch returns a promise you I used await to get the response. To get actual the json data of response, we need to await again on
response.json()
returns a promise.Now we have data but you want only the names of player. So basically here we want the same number of data but in a different format so I used
map
function ofArray
which helps in transform the array.