Home > database >  I don't know how to print all the values ​of an array
I don't know how to print all the values ​of an array

Time:12-02

my name is Jan, I have to do a project for high school, the fact is that I have made a code to access an api, but I cannot display the results of an array that has the api on the screen. This is the code : `

document.querySelector("button").addEventListener("click", getCoin); 

function getCoin(){
    let coin = document.querySelector("input").value.split(" ").join(" ")
    console.log(coin)
    
    fetch("https://open.er-api.com/v6/latest/"   coin)
    .then (res => res.json())
    .then (data => {
      console.log(data.rates)
      

      
      document.querySelector("#coinName").innerText = data.base_code
      document.querySelector("#coinRates").innerText = data.rates
      document.querySelector("#coinProvider").innerText = data.provider
      document.querySelector("#coinTime").innerText = data.time_last_update_utc
      document.querySelector("#coinProxTime").innerText = data.time_next_update_utc
      
    })

}

` It only works if I indicate a specific coin at document.querySelector("#coinRates").innerText = data.rates, and what I want is for it to show me all the values ​​on the screen. I would be very grateful if you could help me.

I have tried with a querySelectALL, also with the for loop, although I think I have done it wrong

CodePudding user response:

Use Object.keys():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Object.keys(data).forEach( key => console.log( data[key] ) );

CodePudding user response:

forEach-loop should do the job in your case.

like the following:

function getCoin() {
  let coins = document.querySelectorAll("input");
  console.log(coins);

  coins.forEach((coin) => {
    coin.value.split(" ").join(" ");
    fetch("https://open.er-api.com/v6/latest/"   coin)
      .then((res) => res.json())
      .then((data) => {
        console.log(data.rates);
        document.querySelector("#coinName").innerText  = data.base_code;
        document.querySelector("#coinRates").innerText  = data.rates;
        document.querySelector("#coinProvider").innerText  = data.provider;
        document.querySelector("#coinTime").innerText  =
          data.time_last_update_utc;
        document.querySelector("#coinProxTime").innerText  =
          data.time_next_update_utc;
      });
  });
}
  • Related