小编典典

JavaScript查找json值

json

我需要在国家(地区)的json列表中进行搜索。json就像:

[ 
{"name": "Afghanistan", "code": "AF"}, 
{"name": "Åland Islands", "code": "AX"}, 
{"name": "Albania", "code": "AL"}, 
{"name": "Algeria", "code": "DZ"}
]

我仅从数据库中获取代码,并会输出整个名称。因此,如果我得到“ AL”,我想从json“ Albania”中检索


阅读 591

收藏
2020-07-27

共1个答案

小编典典

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
  }
}
2020-07-27