我需要在json国家列表中进行搜索。json类似于:
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
]
我只从数据库中获得代码,并将输出整个名称。因此,如果我得到"AL“,我想从json”阿尔巴尼亚“检索。
发布于 2013-10-09 00:57:06
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
发布于 2013-10-09 01:09:59
我建议使用JavaScript的数组方法filter()
通过值来标识元素。它通过使用“函数来测试数组的每个元素。返回true以保留元素,否则返回false”来过滤数据。
下面的函数过滤数据,返回回调返回true
的数据,即data.code
等于请求的国家代码。
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
请看下面的演示:
var data = [{
"name": "Afghanistan",
"code": "AF"
}, {
"name": "Åland Islands",
"code": "AX"
}, {
"name": "Albania",
"code": "AL"
}, {
"name": "Algeria",
"code": "DZ"
}];
function getCountryByCode(code) {
return data.filter(
function(data) {
return data.code == code
}
);
}
var found = getCountryByCode('DZ');
document.getElementById('output').innerHTML = found[0].name;
<div id="output"></div>
发布于 2013-10-09 00:54:55
首先将此结构转换为“字典”对象:
dict = {}
json.forEach(function(x) {
dict[x.code] = x.name
})
然后简单地
countryName = dict[countryCode]
对于国家/地区列表,这并不重要,但对于较大的列表,此方法可确保即时查找,而简单的搜索将取决于列表大小。
https://stackoverflow.com/questions/19253753
复制相似问题