简体   繁体   中英

Not looping through JSON Object Correctly

Im currently trying to make my own crypto watchlist. Im using the CoinRankingAPI ( https://developers.coinranking.com/api/documentation/coins ). Im trying to loop through the coin data in order to retrieve the price, but I get an error stating that the object im trying to iterate over isn't irritable. Source code will be below. Any help would be greatly appreciated!

 const key = 'XXXX'; const url = 'https://api.coinranking.com/v2/coins?' + key; //Loads Stats Data function loadPrices() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var coins = JSON.parse(this.responseText); // get 'data' key inside response var price = coins.data; // loop all the teams for (var coin of price) { // print full name and abbreivation document.getElementById("hello").innerHTML += "<br />" + coin["price"]; } } }; xhttp.open("GET", url, true); xhttp.send(); }

After reviewing the expected response from the provided link, it returns the coins as an object, that contains data value, which in turn contains the coins . You also have an issue in how you build your request and handling the event. So, in order to iterate over the coins try this code:

xhttp.onreadystatechange = function(e) {
    const req = e.target;

    if (req.readyState == 4 && req.status == 200) {
        const response = JSON.parse(req.response);

        // get 'data' key inside response
        const coins = response.data.coins;

        for (let coin of coins) {
            document.getElementById("hello").innerHTML += "<br />" + coin["price"] ;
        }
    }
}

But at the same time, you can use fetch API and async / await which will simplify your code. So, let me provide a better/optimized version of your code:

const key = 'XXXX';
const url = 'https://api.coinranking.com/v2/coins?' + key;

//Loads Stats Data
async function loadPrices() {
    const response = await fetch(url);
    
    const coins = (await response.json()).data.coins;

    const helloElm = document.getElementById("hello");


    // loop all the teams
    let output = '';
    for (var coin of coins) {
        // print full name and abbreivation
        output += "<br />" + coin["price"] ;
    }
    helloElm.innerHTML = output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM