JavaScript에서 json 값 찾기
국가 목록을 검색해야 합니다.json은 다음과 같습니다.
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
]
데이터베이스에서 코드만 가져와 전체 이름을 출력합니다.그래서 만약 'AL'이 된다면 json 'Albania'에서 취득하고 싶다.
값을 기준으로 요소를 식별하기 위해 JavaScript의 Array 메서드를 사용하는 것이 좋습니다.어레이의 각 요소를 테스트하는 함수를 사용하여 데이터를 필터링합니다.요소를 유지하려면 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>
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
}
}
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]
국가 목록의 경우 이는 크게 중요하지 않지만, 더 큰 목록의 경우 이 방법은 즉각적인 검색을 보장하는 반면, 순진한 검색은 목록 크기에 따라 달라집니다.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
예:
getObjectByValue(data, "code", "DZ" );
언급URL : https://stackoverflow.com/questions/19253753/javascript-find-json-value
'programing' 카테고리의 다른 글
| AngularJS: 동시에 업로드되는 각 파일의 상태를 추적합니다. (0) | 2023.03.06 |
|---|---|
| AJAX 응답으로 쿠키를 설정할 수 있습니까? (0) | 2023.03.06 |
| 'toBeInTheDocument' 속성이 'Matchers' 유형에 없습니다. (0) | 2023.02.18 |
| Java에서 JSON을 XML로 변환 (0) | 2023.02.15 |
| 이름이 지정되지 않은 다른 CacheManager가 동일한 VM에 이미 있습니다(ehCache 2.5). (0) | 2023.02.15 |