Reputation:
I have an array that looks like this. I have a countries array containing objects with name
and code
. Given the country name I want to return the country code.
var countries = [
{
name: 'United States',
code: 'US'
},
{
name: 'Spain',
code: 'ES'
}
];
I know I can do something like this, but I am sure there must be a tidier way to do this:
var code;
getCountryFromCode(country) {
for (var i = 0; i < countries.length; i++) {
if (countries[i].name === country) {
code = countries[i].code;
}
}
}
Upvotes: 3
Views: 81
Reputation: 13953
You can use Array#find()
var countries = [
{
name: 'United States',
code: 'US'
},
{
name: 'Spain',
code: 'ES'
}
];
var countryName = "Spain";
console.log(countries.find(c=>c.name===countryName).code);
Upvotes: 3