javascriptobjectcurrency

Display Object values from an API object


I'm trying to create a Currency Conversion using an API, but I'm struggling finding out how to match the currency with it's value.

<div class="container">
    <div class="form">
        <div class="grid-container">
            <div class="currency-from">
                <input type="number" id="main-currency">
                <select onchange="changeCurrency()" id="mainCurrency">
                </select>
            </div>
            <div class="currency-to">
                <input type="number">
                <select id="otherCurrency">
                    <option value="EUR">EUR</option>
                </select>
            </div>
        </div>
        <br>
        <input type="number" name="" id="" disabled>
</div>
const mainCurrency = document.getElementById('mainCurrency');
const inputCurrency = document.getElementById('main-currency');

function changeCurrency() {

    fetch(`https://open.er-api.com/v6/latest/USD`)
    .then(response => {
        return response.json();
    })
    .then(currency => {


        for (const [key, value] of Object.entries(currency.rates)) {
            const currencyName = document.createElement('option');
            currencyName.innerHTML = key;
            currencyName.text = key;
            mainCurrency.appendChild(currencyName);
            inputCurrency.value = value;
          }
    })
}

changeCurrency()

It's always giving me the last value of the object.


Solution

  • One way is to keep the data in memory as a variable. Then get the matching value for a specific currency by looking up the key.

    Demo: jsfiddle

    const mainCurrency = document.getElementById('mainCurrency');
    const inputCurrency = document.getElementById('main-currency');
    var rates = []
    
    function loadCurrencies() {
    
        fetch(`https://open.er-api.com/v6/latest/USD`)
        .then(response => {
            return response.json();
        })
        .then(currency => {
            // store this 
            rates = currency.rates
            for (const [key, value] of Object.entries(currency.rates)) {
                const currencyName = document.createElement('option');
                currencyName.text = key;
                mainCurrency.appendChild(currencyName);
              }
        })
    }
    
    loadCurrencies()
    
    function changeCurrency(select) {
      var key = select.value
      var value = rates[key]
      inputCurrency.value = value
    }