So I'm working on a project where I need to build a bar chart from a dataset fetched from a json resource. json format is at the following link: https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json
I saved the array into the variable named ‘dataset’. When trying to use the dataset in a d3 query (just for testing it), it appears that the dataset array is empty, however, with console.log the array contents are successfully printed to the browser console. I could not figure the reason why this is happening. My code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://d3js.org/d3.v6.js"></script>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300&display=swap" rel="stylesheet">
<title>D3 Bar Chart</title>
</head>
<body>
<div id="chart-container">
<h1 id="title">United States GDP</h1>
</div>
<script>
let dataset = [];
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json').then(
response => response.json()).then(
data => {
for(let i = 0; i < data.data.length; i++) {
dataset.push(data.data[i]);
}
});
d3.select('#chart-container').selectAll('p').data(dataset).enter().append('p').text((d) => d[1]);
console.log(dataset);
</script>
</body>
</html>
Console.log output: