我需要在 json 国家/地区列表中进行搜索。json 是这样的:
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
]
我只从数据库中获取代码并输出整个名称。所以如果我得到“AL”,我想从json“Albania”中检索
我需要在 json 国家/地区列表中进行搜索。json 是这样的:
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
]
我只从数据库中获取代码并输出整个名称。所以如果我得到“AL”,我想从json“Albania”中检索
我建议使用 JavaScript 的 Array 方法filter()
按值标识元素。它通过使用“函数来测试数组的每个元素来过滤数据。返回 true 以保留元素,否则返回 false..”
以下函数过滤数据,返回回调返回的数据true
,即其中data.code
等于请求的国家/地区代码。
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
请看下面的演示:
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
}
}
只需find()
以函数式的方式使用 ES6函数:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
或 Lodash _.find:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
首先将此结构转换为“字典”对象:
dict = {}
json.forEach(function(x) {
dict[x.code] = x.name
})
然后简单地
countryName = dict[countryCode]
对于国家列表,这无关紧要,但对于较大的列表,此方法可保证即时查找,而简单搜索将取决于列表大小。
使@showdev答案更加笼统。
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
例子:
getObjectByValue(data, "code", "DZ" );