Raul Rodriguez Raul Rodriguez -4 years ago 95
Javascript Question

Get value of key of object in array based on other key in object

I have an array that looks like this. I have a countries array containing objects with

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

Answer Source

using es6:

 countries.find(x => x.name === 'United States').code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download