How to iterate over objects stored in a JavaScript array

Viewed 57

I'm coding a simple JavaScript currency converter. Pulled the currency data from an API and stored it to a state object. Next, I wanted to add currency name, country and symbol to the app so I'm pulling that data from a Rest Countries API and storing it to "currencies" array.

Here's the code:

export const state = {
  date: [],
  time: {},
  currency: [],
  rates: {},
  result: [],
};

export const getSymbolsCountry = async function (symbol) {
  try {
    const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`);
    const json = await data.json();
    addInfoToSymbol(json[0]);
  } catch (err) {
    console.log(err);
  }
};

function addInfoToSymbol(data) {
  let country = {
    code: data.currencies[0].code,
    symbol: data.currencies[0].symbol,
    flag: data.flag,
    country: data.name,
  };

  state.currency.push(country);
}

Console logging the currency from state shows that it's an array but using map or forEach on it does nothing. console log state.currency Could someone please help me understand what I'm doing wrong cause I can't wrap my head around it.

1 Answers

What do you mean by using map of forEach on it does nothing ?

Here is an example where I use forEach on state.currency and its working perfectly.

const state = {
  currency: []
};

const getSymbolsCountry = async function (symbol) {
  try {
    const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`);
    const json = await data.json();
    addInfoToSymbol(json[0]);
  } catch (err) {
    console.log(err);
  }
};

function addInfoToSymbol(data) {
  let country = {
    code: data.currencies[0].code,
    symbol: data.currencies[0].symbol,
    flag: data.flag,
    country: data.name,
  };

  state.currency.push(country);
}

Promise.all([
  getSymbolsCountry("EUR"),
  getSymbolsCountry("USD"),
  getSymbolsCountry("JPY")
])
.then(() =>
  state.currency.forEach(({code}) => 
    $("#result").append("<li>" + code + "</li>")
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="result"></ul>

Related