skip to Main Content

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


  1. async function nba(){
        const url = "https://www.balldontlie.io/api/v1/players";
        const response = await fetch(url);
        const data = await response.json();
        
        // data is {data: array, meta: object}
        data.data.forEach(item => {
            console.log(item.first_name)
        })
    }
    
    nba();
    
    Login or Signup to reply.
  2. Following code will work for you:

    async function nba(){
        const url = "https://www.balldontlie.io/api/v1/players";
        const response = await fetch(url);
        const result = await response.json();
        
        console.log(result.data.map(player => player.first_name));
    
    }
    
    await nba();
    

    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 of Array which helps in transform the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search