Home > OS >  How to display all players names in the Ball Don't Lie API array
How to display all players names in the Ball Don't Lie API array

Time:02-05

I am doing one of my first projects using the Ball Don't lie API, trying to build my version of an ESPN landing page. I am using https://www.balldontlie.io/api/v1/players. I am using Javascript, I have been stuck for days trying to understand how to display the first and last name of all of the players on the landing page in HTML. I only know how to display one name if I use data.data[0]. I've tried .map, loops, it's just not clicking. I want to be able to display other stats in the array as well. Can anyone help?

This my Javascript code:

async function getPlayers() {
    const response = await fetch ('https://www.balldontlie.io/api/v1/players');
    const data = await response.json();
    const players = data.data;
    console.log(players);
    displayPlayer(players);


}

function displayPlayer(players) {

    const scores = document.getElementById('scores');
    scores.innerHTML = `
    
    ${players.first_name} ${players.last_name}`;

   
}

getPlayers()```


I had tried .map, I've tried loops, I am just not understanding what function is going to show the players. Maybe my orignal code doesn't make sense. I've tried watching Youtube and can't find anyone doing it in simple Javascript.

CodePudding user response:

You can try this in your script and edit points 2. and 4. for better display of what you need to show

// 1. GET request using fetch()
fetch("https://www.balldontlie.io/api/v1/players")
  // Converting received data to JSON
  .then((response) => response.json())
  .then((json) => {
    
  // 2. Create a variable to store HTML table headers
    let li = `<tr><th>ID</th><th>first_name</th><th>height_feet</th><th>height_inches</th> <th>last_name</th><th>position</th><th>im lazy...</th></tr>`;

    // 3. Loop through each data and add a table row
    console-console.log(json.data);
    json.data.forEach((user) => {
      li  = `<tr>
        <td>${user.id}</td>
        <td>${user.first_name} </td>
        <td>${user.height_feet}</td>
        <td>${user.height_inches}</td>
        <td>${user.last_name}</td>
        <td>${user.position}</td>
        <td>${user.team.id}</td>
        <td>${user.team.abbreviation}</td>
        <td>${user.team.city}</td>
        <td>${user.team.conference}</td>
        <td>${user.team.division}</td>
        <td>${user.team.full_name}</td>
        <td>${user.team.name}</td>
      </tr>`;
    });

    // 4. DOM Display result
    document.getElementById("users").innerHTML = li;
  });

And your html body part look like this

    <div>
      <!-- Table to display fetched user data -->
      <table id="users"></table>
    </div>

CodePudding user response:

Your constant players is an array. In order to access a player's information within that array, you would need to index each player to then access their object of key:value pairs.

That is why you can get the first player's name to show when you save players as data.data[0]. This is indicating that you want to access the object in position 0 in the array. If you wanted the second player's information you would reference data.data[1], and so forth.

With trying to keep as much of your original code as possible (and adding some comments), I believe this is what you were trying to achieve.

async function getPlayers() {

  // Fetch the API and convert it to json.
  const response = await fetch ('https://www.balldontlie.io/api/v1/players');
  const data = await response.json();

  // Save the returned data as an array.
  const players = data.data;
  console.log(players);

  // Create an element to display each individual player's information.
  players.array.forEach(player => {
    displayPlayer(player); 
  });

}

function displayPlayer(player) {

  // Grab the element encasing all players.
  const scores = document.getElementById('scores');

  // Create a new element for the individual player.
  const playerContent = document.createElement('div');

  // Add the player's name.
  playerContent.innerHTML = `
    
    ${player.first_name} ${player.last_name}`;

  // Add the player content into the encasing division.
  scores.appendChild(playerContent); 
}

getPlayers()

We will use the forEach() function to index each player's object in the array of data for us, grab your "scores" element you created on your HTML page, then we will "append" (add to the end) each player's information into your "scores" element.

The website link below has some useful information to read that can help you build on your existing code when you want to start adding styling. https://www.thesitewizard.com/javascripts/insert-div-block-javascript.shtml

This site has some useful information on using "promises" when dealing with async functions that will come in handy as you progress in coding. https://www.geeksforgeeks.org/why-we-use-then-method-in-javascript/

These website links were added as of 02/04/2023 (just to add as a disclaimer to the links because who knows what they will do in 2030 O.o).

Hope this helps!

  • Related