Art
@ascpenteadoAll comments
- @SweetCaroline36@ascpenteado
Hi, SweetCaroline36!
Nice job! I think you made it very close to the design.
About reading de JSON file:
You should have gone for the
fetch()
function. The thing is that fetch returns aPromise
and this can make things a little more complex.It would be something like this:
const data = fetch("./data.json") .then((res) => { return res.json(); }) .then((data) => { const amounts = []; data.forEach((x) => { amounts.push(x.amount); }); // ... rest of your code...
Using
.then()
enables you to access the contents of the file. You have to wait until JS reads the file, and then you transform the data from JSON (which is also a Promise) to an object.There is a cleaner way, using
async/await
:async function fetchData() { try { const res = await fetch("./data.json"); const data = await res.json(); return data; } catch (error) { console.error(error); } } const data = await fetchData(); if (data) { const amounts = []; data.forEach((x) => { amounts.push(x.amount); }); // ... rest of your code ...
If you try that I believe that you'll manage to read from the JSON file. :)
If you never heard of Promises or Asynchronous code, there is a lot of good content out there.
Here is one I like: Asynchronous Vs Synchronous Programming
I hope it helps!