使用变量获取特定的数组元素数据

时间:2015-11-28 10:59:21

标签: javascript

有没有办法使用值标识符在数组中查找数据?

示例:在下面的对象中,我想做类似的事情:

for(country in data.countries)
{
    if(country.name === "GB") {return-value-of-country.Clear;}
}

对象示例:

 {
  "countries":[
    {
      "name": "GB",
      "Rain":" url1 ",
      "Clear":" url2 "
    }
    ...
  ]
} 

3 个答案:

答案 0 :(得分:0)

除非您使用ES6或某些外部库,否则没有很好的方法,例如:

var countries = data.countries,
    len = countries.length,
    match, i, country;

for (i = 0; i < len; ++i) {
    country = countries[i];
    if (country.name === 'GB') {
        match = country;
        break;
    }
}

if (match) {
    console.log(match.Clear);
}

答案 1 :(得分:0)

要迭代数组,你需要带索引的循环:

for(var i = 0; i<data.countries.length; ++i) {
    if(data.countries[i].name === "GB") {
        //your value is data.countries[i].Clear;
    }
}

答案 2 :(得分:0)

如果您没有使用像underscore这样的库。

我会这样做:

&#13;
&#13;
var test = {
  "countries":[
    {
      "name": "GB",
      "Rain":" url1_gb",
      "Clear":" url2_gb"
    },
    {
      "name": "FR",
      "Rain":" url1_fr",
      "Clear":" url2_fr"
    },
    {
      "name": "DE",
      "Rain":" url1_de",
      "Clear":" url2_de"
    },

  ]
}

var getClearUrl = function(country) {
  for (var i = test.countries.length - 1; i >= 0; i--) {
    if (test.countries[i].name === country) {
      return test.countries[i].Clear;
      break;
    }
  };  

  return false;
}

var clearUrlGB = getClearUrl('GB');
console.log(clearUrlGB);
&#13;
&#13;
&#13;