Search code examples
javascriptarraysloopsobjectfetch-api

i am trying to loop through and array containing aobject


I am trying to create a loop to display every element from an api using fetch however the api has this structure :

{
  "pokemons": [
    {
      "id": 1,
      "name": "germignon",
      "level": 80,
      "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
      "abilities": [
        {
          "name": "vampigrain",
          "icon": "🌿",
          "power": 60,
          "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
        }
      ],
      "background_color": "#E0ED94"
    },
    {
      "id": 2,
      "name": "kaiminus",
      "level": 28,
      "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/5.png",
      "abilities": [
        {
          "name": "foam",
          "icon": "💧",
          "power": 30,
          "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
        },
        {
          "name": "hydrocannon",
          "icon": "💧",
          "power": 150,
          "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
        }
      ],
      "background_color": "#A1E3FF"
    },

and i have troubles accessing the "abilities" withing pokemons Can anyone help please

i have tried this :


fetch('https://pokeapi-enoki.netlify.app/').then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.json();
   
  })
  .then((response) => {
   
    let data=" ";
    response.pokemons.map((value)=>{
 
  
      
   
    data+=  `  <div  class="Card" id="${value.id}" style="background-color: ${value.background_color }" >
        <div class="header"> <p class="name">${value.name }</p>
         <p class = "level" > Niv.${value.level }${value.abilities.icon}</p>
     </div>
         <div class="image">
             <img src="${value.image }" alt="" srcset="">
         </div>
        <div >
   <div class="abilities" >
        <span class="AbIcon">${value.abilities.name}</span>
        <span class="AbName">${value.abilities.icon}</span>
        <span class="AbLevel">${value.abilities.power}</span>  
        <p>${value.abilities.description}</p>
    </div>
    </div>`
      

    });
    document.querySelector("#carContainer").innerHTML =data;

   
  }).catch((error)=>
  console.log(error))

but its not working . i can't display anything in the abilities it returns underfined

the nested for lop i have tried

    let data=" ";
  for(var i = 0; i < response.pokemons.length; i++) {
     for(var a = 0; a < response.pokemons[i].abilities.length; a++) {
     data+= `<div class="carConainer">
      <div  class="Card" id="${response.pokemons[i].id}" style="background-color: ${response.pokemons[i].background_color }" >
          <div class="header"> <p class="name">${response.pokemons[i].name }</p>
           <p class = "level" > Niv.${response.pokemons[i].level }${response.pokemons[i].abilities[0].icon}</p>
       </div>
           <div class="image">
               <img src="${response.pokemons[i].image }" alt="" srcset="">
           </div>
     
         
          <div >
     <div class="abilities" >
          <span class="AbIcon">${response.pokemons[i].abilities[a].icon}</span>
          <span class="AbName">${response.pokemons[i].abilities[a].name}</span>
          <span class="AbLevel">${response.pokemons[i].abilities[a].power}</span>  
          <p>${response.pokemons[i].abilities[a].description}</p>
      </div>`
      }}
    document.querySelector("#carContainer").innerHTML =data;

   
  }).catch((error)=>
  console.log(error))

Solution

  • As suggested in comments, abilities is an array of objects. So I've changed the code accordingly, adding an inner loop over the abilites.

    var response = {
      "pokemons": [{
          "id": 1,
          "name": "germignon",
          "level": 80,
          "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
          "abilities": [{
            "name": "vampigrain",
            "icon": "🌿",
            "power": 60,
            "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
          }],
          "background_color": "#E0ED94"
        },
        {
          "id": 2,
          "name": "kaiminus",
          "level": 28,
          "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/5.png",
          "abilities": [{
              "name": "foam",
              "icon": "💧",
              "power": 30,
              "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
            },
            {
              "name": "hydrocannon",
              "icon": "💧",
              "power": 150,
              "description": "Pokem ipsum dolor sit amet Technical Machine Shuckle Magneton Earthquake Marsh Badge Raichu. Dragon Pokemon Fan Club Chairman Golem Dodrio Psychic to denounce the evils of truth and love Marshtomp. Earth Badge Shuckle Mew Celadon Department Store Snorlax"
            }
          ],
          "background_color": "#A1E3FF"
        },
      ]
    }
    
    
    var data = ""
    response.pokemons.map((value) => {
      var html_abilities = "";
      value.abilities.forEach(function(ability) {
        html_abilities += `
          <div class="ability">
            <span class="AbIcon">${ability.name}</span>
            <span class="AbName">${ability.icon}</span>
            <span class="AbLevel">${ability.power}</span>
            <p>${ability.description}</p>
          </div>
        `;
      })
    
    
    
      data += ` 
        <div class="Card" id="${value.id}" style="background-color: ${value.background_color }">
          <div class="header">
            <p class="name">${value.name }</p>
            <p class="level"> Niv.${value.level }${value.abilities.icon}</p>
          </div>
          <div class="image">
            <img src="${value.image }" alt="" srcset="">
          </div>
          <div>
            <div class="abilities">
              ${html_abilities}
            </div>
          </div>
        </div>  
      `
    
    
    });
    document.querySelector("#carContainer").innerHTML = data;
    <div id="carContainer"></div>