Tuesday 25 December 2018

How to map JSON Data in Javascript ES6




I would like to get the JSON data from Coinmarket.



I get the data but can't map the Data.



below my Code




    const p = document.querySelector('p');
let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
let coinsdata = [];
fetch(endpoint)
.then(blob => blob.json()
.then(data => coinsdata.push(...data)));

console.log(coinsdata);
coinsdata.map(coindata => {
return p.innerHTML = coindata.id;

});

Answer



The issue with you code is that you have not properly managed the asynchronous xhr call. The code is written outside 'then' code block which is why you are not seeing anything.



The Solution:



let p = document.querySelector('p');
const endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)

.then(blob => blob.json())
.then(data => {
data.map(obj => p.innerHTML += ("\n" + JSON.stringify(obj)) );
});


This will print the objects in sequence. You can change the code as per your requirement. This was just to show the core idea.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...