Jack Barham
Jack Barham

Reputation: 3219

Trying to get an object value in from a key in Javascript

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' },
    ...
]

Upvotes: 0

Views: 1333

Answers (3)

Jack Barham
Jack Barham

Reputation: 3219

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
}

Upvotes: 0

frodo2975
frodo2975

Reputation: 11783

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].

Upvotes: 2

rossipedia
rossipedia

Reputation: 59437

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.

Upvotes: 3

Related Questions