I'm trying to get a country label (name) from a value (country code) in an object.
In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.
In the template:
countryLabel () {
var countries = require('../../plugins/countries')
var countryCode = this.content.country
function getLabelByValue(countries, countryCode) {
return Object.keys(countries).find(label => countries[value] === countryCode)
}
}
From a list of countries:
module.exports = [
{ value: 'AF', label: 'Afghanistan' },
{ value: 'AX', label: 'Aland Islands' },
{ value: 'AL', label: 'Albania' },
{ value: 'DZ', label: 'Algeria' },
{ value: 'AS', label: 'American Samoa' },
{ value: 'AD', label: 'Andorra' },
{ value: 'AO', label: 'Angola' },
{ value: 'AI', label: 'Anguilla' },
{ value: 'AQ', label: 'Antarctica' },
{ value: 'AG', label: 'Antigua and Barbuda' },
...
]
3 Answers 3
You probably don't want to be calling Object.keys
on an array.
Something like this is probably more what you want:
function getLabelByValue(countries, countryCode) {
const entry = countries.find(item => item.value === countryCode);
return entry ? entry.label : null;
}
The problem is that calling Object.keys
on an array will return an array of numbers that have been converted to strings:
> console.log(Object.keys(['this', 'is', 'an', 'array']));
['0', '1', '2', '3']
Since your exports
is already an array, you can call find()
on it directly.
1 Comment
A better way to do this would be to use an object, which is always the fastest way to lookup anything in javascript because objects are dictionaries. So if you changed your export to look like:
{
AF: 'Afghanistan',
AX: 'Aland Islands',
etc...
}
then you'd be able to do instant lookups by doing countries[countryCode]
.
3 Comments
Based on rossipedia's answer this is working for me:
countryLabel () {
const countries = require('../../plugins/countries')
return countries.find(item => item.value === this.content.country).label
}
1 Comment
this
context. If you decide to change your arrow function into a standard function, this code will break.
0->n
. I think what you want is simplycountries.find(country => country.value === countryCode)