我需要在国家/地区的 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
,即 wheredata.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>
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
}
}
只需以函数式的方式使用 ES6find()
函数:
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" );