首页 > 解决方案 > 如何提高我的 javascript 的质量 - 给定 2 个 json 格式数组

问题描述

const countryList = [{"countryId":1,"countryQuote":"USDKRW","countryCode":"KRW","countryName":"\uD55C\uAD6D"},{"countryId":2,"countryQuote":"USDJPY","countryCode":"JPY","countryName":"\uC77C\uBCF8"},{"countryId":3,"countryQuote":"USDPHP","countryCode":"PHP","countryName":"\uD544\uB9AC\uD540"}];
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);

我想找到currencyRate使用itemId.

常量值由服务器给出。

我有一个countryIdHTML,我想currencyRate用这 2 个数组找到。

数组中的每个countryQuote键都是可连接的。

我只需要currencyRate使用蛮力搜索找到,但我想改进这段代码。

我应该怎么搜索它?

标签: javascript

解决方案


这个解决方案能满足您的需求吗?

使用find而不是forEach :)

我添加了一些未定义值的检查。

const countryList = [{"countryId":1,"countryQuote":"USDKRW","countryCode":"KRW","countryName":"\uD55C\uAD6D"},{"countryId":2,"countryQuote":"USDJPY","countryCode":"JPY","countryName":"\uC77C\uBCF8"},{"countryId":3,"countryQuote":"USDPHP","countryCode":"PHP","countryName":"\uD544\uB9AC\uD540"}];
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:从此由于 ES6 存在数组的本机查找方法;一旦找到第一个匹配项并返回值,它将停止枚举数组。

因此,使用find比检查数组中的每个元素要高效得多(如果找到的话)。


推荐阅读