javascript - 如何提高我的 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
.
常量值由服务器给出。
我有一个countryId
HTML,我想currencyRate
用这 2 个数组找到。
数组中的每个countryQuote
键都是可连接的。
我只需要currencyRate
使用蛮力搜索找到,但我想改进这段代码。
我应该怎么搜索它?
解决方案
这个解决方案能满足您的需求吗?
使用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比检查数组中的每个元素要高效得多(如果找到的话)。
推荐阅读
- c# - 下载文件并通过 FolderbrowserDialog 选择其位置
- java - 区分全名、公司名称和职务
- vue.js - Vue(x) 在使用 Vue.set(...) 时不是反应式的,但在使用 Object.assign 时是反应式的,为什么?
- angular - 订阅商店切片 - ngrx
- javafx - 在 Raspberry Pi 3 上使用 JavaFX 11 播放 mp3
- c# - 迭代时如何突破 IAsyncEnumerable?
- alibaba-cloud - 无法通过 apache2 访问端口 80 上的站点?
- google-cloud-platform - Google Cloud gcloud 命令显示“区域 'us-east1-b' 中不存在名称为 'f1-micro--subnet=default' 的机器类型”
- algorithm - 为“不倒翁问题”开发一种算法
- c# - C#中2个位图图像之间的距离/相似度