我需要在国家(地区)的json列表中进行搜索。json就像:
[ {"name": "Afghanistan", "code": "AF"}, {"name": "Åland Islands", "code": "AX"}, {"name": "Albania", "code": "AL"}, {"name": "Algeria", "code": "DZ"} ]
我仅从数据库中获取代码,并会输出整个名称。因此,如果我得到“ AL”,我想从json“ Albania”中检索
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 } }