Reputation: 1248
I am trying to grab the country name from an array called countries that has the countryCode as the keys and the country name as the values. I am extracting the country code from result on ajax call to database. when i get the country code i need to scan through the countries array and pull the value that matches the country code.
Any help would be greatly appreciated, thanks. No outside libraries to solve just jquery || javascript please.
Here is my attempt to solve this:
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'];
}
});
}
Here is the countries array of objects:
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'}
];
Upvotes: 1
Views: 1766
Reputation: 1248
Here is the answer i ended up going with thank to @adeneo. I appreciate everyone else's help as well.
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'];
}
});
}
As for the countries array i made it an object with keys instead.
var countries = {'AU': 'Australia', 'US': 'United States'};
Upvotes: 1
Reputation: 1086
you can use filter and check the property
countries.filter(a=> a.hasOwnProperty(countryCode.toUpperCase()) ? a : null )
Upvotes: 1