user7597670
user7597670

Reputation:

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

Answers (2)

Weedoze
Weedoze

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

Ain
Ain

Reputation: 419

using es6:

 countries.find(x => x.name === 'United States').code

Upvotes: 3

Related Questions