JavaScript 查找 json 值

我需要在一个 json 国家列表中搜索 json 是这样的:

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

我从数据库只有代码,并会输出整个名称。所以如果我得到了“ AL”我想从“阿尔巴尼亚”的 json 那里取回

352781 次浏览

首先将这个结构转换为一个“ dictionary”对象:

dict = {}
json.forEach(function(x) {
dict[x.code] = x.name
})

然后简单地

countryName = dict[countryCode]

对于一个国家列表,这并不重要,但对于较大的列表,这种方法保证了即时查找,而初始搜索将取决于列表的大小。

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
}
}

我建议使用 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 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>

Here's a JSFiddle.

使得 @ showdev的答案更一般化。

var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};

例如:

getObjectByValue(data, "code", "DZ" );

只要以功能性的方式使用 ES6 find()功能:

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 < a href = “ https://lodash.com/docs/4.17.11 # find”rel = “ norefrer”> _. 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>