我正在尝试从名为country的数组中获取国家/地区名称,该数组以countryCode作为键,国家/地区名称作为值。我从ajax调用数据库的结果中提取国家代码。当我得到国家代码时,我需要扫描countries数组并提取与国家/地区代码匹配的值。
非常感谢任何帮助,谢谢。没有外部库只能解决jquery || javascript请。
我试图解决这个问题:
function getAllDistributors(){
$j.ajax({
url: '<?php echo Mage::getBaseUrl(); ?>distributor/index/getAllDistributors',
type: "GET",
success: function(data) {
//console.log(data.map(JSON.parse));
results = JSON.parse(data);
console.log(results.distributers);
var distributors = results.distributers;
distributors.forEach(function(distributor){
var countryCode = distributor.country_code;
console.log(countryCode);
// returns each country code ex. 'us'
});
//var countryName = results['country'];
//var distributor = results['distributers'];
}
});
}
以下是国家/地区对象数组:
var countries = [
{'AT': 'Austria'},
{'BU': 'Bulgaria'},
{'CZ': 'Czech Republic'},
{'DK': 'Denmark'},
{'EE': 'Estonia'},
{'FI': 'Finland'},
{'FR': 'France'},
{'DE': 'Germany'},
{'HU': 'Hungary'},
{'IE': 'Ireland'},
{'IT': 'Italy'},
{'NL': 'Netherlands'},
{'NO': 'Norway'},
{'PL': 'Poland'},
{'PT': 'Portugal'},
{'RM': 'Romania'},
{'SI': 'Slovenia'},
{'ES': 'Spain'},
{'SE': 'Sweden'},
{'CH': 'Switzerland'},
{'TR': 'Turkey'},
{'GB': 'United Kingdom'},
{'CA': 'Canada'},
{'MX': 'Mexico'},
{'PR': 'Puerto Rico'},
{'US': 'USA'},
{'AR': 'Argentina'},
{'BR': 'Brazil'},
{'AU': 'Australia'},
{'IN': 'India'},
{'MY': 'Malaysia'},
{'NZ': 'New Zealand'},
{'CN': 'People\'s Republic of China'},
{'SG': 'Singapore'},
{'SK': 'South Korea'},
{'TW': 'Taiwan'},
{'UA': 'United Arab Emirates'}
];
答案 0 :(得分:1)
您可以使用过滤器并检查属性
countries.filter(a=> a.hasOwnProperty(countryCode.toUpperCase()) ? a : null )
答案 1 :(得分:1)
这是我最后感谢@adeneo的答案。我也很感谢其他人的帮助。
function getAllDistributors(){
$j.ajax({
url: '<?php echo Mage::getBaseUrl(); ?>distributor/index/getAllDistributors',
type: "GET",
success: function(data) {
//console.log(data.map(JSON.parse));
results = JSON.parse(data);
console.log(results.distributers);
var distributors = results.distributers;
distributors.forEach(function(distributor){
var cc = distributor.country_code.toUpperCase();
countryCode = cc.replace("\\s+","");
console.log(countries[countryCode]);
});
//var countryName = results['country'];
//var distributor = results['distributers'];
}
});
}
至于国家数组我改为使用键作为对象。
var countries = {'AU': 'Australia', 'US': 'United States'};