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.
2👍
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]
.
0👍
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
}
Source:stackexchange.com