Skip to content
Advertisement

How to improve quality of my javascript – given 2 json-format array

const countryList = [{"countryId":1,"countryQuote":"USDKRW","countryCode":"KRW","countryName":"uD55CuAD6D"},{"countryId":2,"countryQuote":"USDJPY","countryCode":"JPY","countryName":"uC77CuBCF8"},{"countryId":3,"countryQuote":"USDPHP","countryCode":"PHP","countryName":"uD544uB9ACuD540"}];
const currencyQuoteList = [{"countryQuote":"USDKRW","currencyRate":1162.685028},{"countryQuote":"USDJPY","currencyRate":104.40402},{"countryQuote":"USDPHP","currencyRate":48.480296}];

let itemId = 1;
let countryQuote;
let countryRate;

countryList.forEach(element => {
    if(itemId == element.countryId) {
        countryQuote = element.countryQuote;
    }
});
console.log("countryQuote : " + countryQuote);

currencyQuoteList.forEach(element => {
    if(countryQuote == element.countryQuote) {
        countryRate = element.currencyRate;
    }
})
console.log("countryRate : " + countryRate);

I would like to find currencyRate using itemId.

Const values are given by the server.

I have a countryId in HTML, and I’d like to find currencyRate With these 2 arrays.

Each countryQuote key in arrays would be joinable.

I just have to find currencyRate using brute-force searching, but I would like to improve this code.

What should do I search for it?

Advertisement

Answer

Does this solution can suit your needs?

Use find instead of forEach 🙂

I have added a little bit of checks for undefined values.

const countryList = [{"countryId":1,"countryQuote":"USDKRW","countryCode":"KRW","countryName":"uD55CuAD6D"},{"countryId":2,"countryQuote":"USDJPY","countryCode":"JPY","countryName":"uC77CuBCF8"},{"countryId":3,"countryQuote":"USDPHP","countryCode":"PHP","countryName":"uD544uB9ACuD540"}];
const currencyQuoteList = [{"countryQuote":"USDKRW","currencyRate":1162.685028},{"countryQuote":"USDJPY","currencyRate":104.40402},{"countryQuote":"USDPHP","currencyRate":48.480296}];

// The item identifier
const itemId = 1;

// Search country using itemId
const country = countryList.find(c => c.countryId === itemId);

if(country !== undefined) {
  // Country found

  // Search a match in currencyQuote using countryQuote found
  const currency = currencyQuoteList.find(c => c.countryQuote === country.countryQuote);
  
  if(currency !== undefined) {
    // Currency found !!!
    console.log(`Country: ${country.countryQuote}`)
    console.log(`Currency Rate: ${currency.currencyRate}`);
  } else {
    // Currency not found
    console.log("Invalid countryQuote :(");
  }
} else {
  // Country not found
  console.log("Invalid itemId :(");
}

PS: From this: “Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value.

So, using find is far more efficient (if found) rather than check every single element in the array.

Advertisement