有没有办法使用值标识符在数组中查找数据?
示例:在下面的对象中,我想做类似的事情:
for(country in data.countries)
{
if(country.name === "GB") {return-value-of-country.Clear;}
}
对象示例:
{
"countries":[
{
"name": "GB",
"Rain":" url1 ",
"Clear":" url2 "
}
...
]
}
答案 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这样的库。
我会这样做:
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;