인 경우 JSON 파일에 여러 객체 배열이있는 객체가 있습니다. 개체의 값이 특정 숫자와 같은 경우 함수를 호출하고 싶습니다. 같으면 해당 값을 가진 객체가 선택된 div에 입력됩니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?JSON - 객체 값이
예 :
나는 "프로파일"개체가 있고 개체 "카테고리"숫자 "1"와 같은지 비교하고 싶다. 그렇다면 해당 객체를 첫 번째 ".contentBox .viewed"에 입력하십시오. "category"객체가 숫자 "2"와 같은 경우 두 번째 ".contentBox .viewed"에 해당 객체를 입력합니다.
json으로 데이터
: 현재 JS의{
"profiles": [
{ "firstName" : "John", "lastName" : "Doe", "gender": "male", "category": 1 },
{ "firstName" : "Jane", "lastName" : "Austen", "gender": "female", "category": 1 },
{ "firstName" : "Alexander", "lastName" : "Beth", "gender": "male", "category": 1 },
{ "firstName" : "Sarah", "lastName" : "Kelly", "gender": "female", "category": 2 },
{ "firstName" : "Rachel", "lastName" : "Haiworth", "gender": "female", "category": 2 },
{ "firstName" : "Thomas", "lastName" : "Alfae", "gender": "male", "category": 2 },
{ "firstName" : "William", "lastName" : "Lee", "gender": "male", "category": 2 }
]
}
샘플 :
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
responseObject.profiles.sort(function(a, b) {
return SortAlphabetically(a.firstName, b.firstName);
});
var newViewers = '';
for (var i = 0; i < responseObject.profiles.length; i++) {
newViewers += '<span class="user">' + responseObject.profiles[i].firstName + ' ';
newViewers += responseObject.profiles[i].lastName + '</span>';
newViewers += ' ';
}
//Update Page With New Content
var viewerSection = $('div.viewed');
viewerSection.html(newViewers);
checkViewers();
}
};
xhr.open('GET', 'data.json', true);
xhr.send(null);
내가 "profiles.category.val() === 1
의 라인을 따라 뭔가 "가 작동 할 경우 확실하지 않다 또는 더 나은 경로가있는 경우.
현재보기 및 완료
JS의 기본 정렬 정렬 사전 순으로 정렬하지 않습니까? –
당신의 삶을 편하게 할 수있는 Array # filter (google mdn 필터) –
'if (responseObject.profiles [i] .category == 1)' – Barmar