Parsing json data in create-react-app

I have the following code which returns a JSON data from the given API.

let ratesData = getRatesFromDates(startDateRate, endDateRate, baseCurrency, targetCurrency);
  async function getRatesFromDates(startDate, endDate, baseCurrency, targetCurrency) {
    try {
      let response = await fetch('' +
                                    startDate + '&end_at=' + endDate + '&symbols=' + baseCurrency + ',' + targetCurrency);
      let jsonData = await response.json();
      return jsonData.rates;
     } catch(error) {

And the following is output in the console


How do I loop through these data to make use and display them on the webpage or pass certain values to other functions?

You can use Object.keys or Object.entries. For example if you want to loop through an object like const obj = {a: 1, b: 2, c: 3}, you can get the keys or key-value pairs like:

const keys = Object.keys(obj); // keys = [a, b, c]


const entries = Object.entries(obj); // entries = [[a, 1], [b, 2], [c, 3]];
1 Like

The reason you are seeing all that Promise stuff in the console output is because you are calling console.log before the Promise has resolved. You have to call it inside the getRatesFromDates function after jsonData has received a value from response.json. jsonData will be an ordinary JS object that you can iterate using any of the usual methods for iterating an object.


Thanks for the help. I think I managed to parse the data now…
However, I am having a bit of a display problem.

Here is the code for converting the object as array

const getListCurrencyExchangeRate = () => {
    getRatesFromDates(startDateRate, endDateRate, baseCurrency, targetCurrency)
    .then( res =>{
      const list = [];
      Object.keys(res).forEach(key => {
        list.push({ date: key,
                    baseCurrencyName: baseCurrency,
                    targetCurrencyName: targetCurrency,
                    baseCurrencyValue: res[key][baseCurrency],
                    targetCurrencyValue: res[key][targetCurrency]

Here is the code for my table

    {, index) =>
    <th>{rateArray.baseCurrencyName} -> {rateArray.targetCurrencyName}</th>)}
  {, index) =>
    (<tr key={index}>
    {/*  <td>{rateArray.baseCurrencyName}</td>
      <td>{(Math.round((rateArray.baseCurrencyValue + Number.EPSILON) * 100) / 100).toFixed(2)}</td>
      <td>{rateArray.targetCurrencyName}:</td> */}
      <td>{(Math.round((rateArray.targetCurrencyValue + Number.EPSILON) * 100) / 100).toFixed(2)}</td>

Seems like it looped through the array and display the table header n times depends on the array size… I tried doing something like rateArray[0].baseCurrencyName but it returns error. Is there a way to only display baseCurrencyName and targetCurrencyName one time?

Edit: Although I can use CSS to hide the extra table header, just curious if there is a proper way of doing it…