基于对象的其他键,获取数组中对象的键值。

时间:2021-06-14 20:14:44

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

2 个解决方案

#1


2  

using es6:

使用es6:

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

#2


2  

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

#1


2  

using es6:

使用es6:

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

#2


2  

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

相关文章