2016-09-22 2 views
-1

나는 다음 개체있다 : 나는 모든 값을 반복하고 다음과 같이 테이블에 새 행에이를 표시으로 반복

response = 
    { 
     "5": { 
      "name": "surgeon bueno", 
      "country": "Spain", 
      "antiquity": "renewal", 
      "amount": "2686.97 USD", 
      "sellers": { 
       "Frank": "2690.58 USD", 
       "Bob": "1690.58 USD", 
      } 
     }, 
     "11": { 
      "name": "Alex Lloyd", 
      "country": "American Samoa", 
      "antiquity": "new client", 
      "amount": "0.0 USD" 
     }, 
     "12": { 
      "name": "alex lloyd", 
      "country": "Aruba", 
      "antiquity": "new client", 
      "amount": "0.0 USD" 
     } 
    } 

그리고, 나는 새를 추가하고 싶습니다 예를 들어 JSON에 "sellers"이있는 행은 존재하는 경우 "surgeon bueno" 같은 방법 나뿐만 아니라 그들을 통해 반복하고 새 행을 표시 할 수 있습니까? 그들에는 열쇠 이름이 없기 때문에. 이 약자로

내가 지금은 판매자가있는 경우 행을 추가하고 해당 데이터를 표시하려면, 코드입니다.

$.each(response, function(i, item) { 
      $('#modal-table tbody').append("<tr class='grey'><td>" + item.name + "</td><td>" + item.country + "</td><td>" + item.antiquity + "</td><td>" + item.amount + "</td>"); 

     }); 

이것은 기존 게시물과 비교 된 새로운 코드입니다.

+2

가능한 중복 (http://stackoverflow.com/questions/39636048/detect-if-object-is-empty-or- not-jquery) – guradio

답변

0

당신은 아마 바닐라 자바 ​​스크립트를 사용하여 반복 할이 객체를 반복하고 모든 키에 var i을 설정합니다

for (var i in response) { 
    $('#modal-table tbody').append("<tr class='grey'><td>" + response[i].name + "</td><td>" + response[i].country + "</td><td>" + response[i].antiquity + "</td><td>" + response[i].amount + "</td>"); 
} 

. [객체가 비어 있거나하지 JQuery와 경우 감지]의

$(function() { 
 
    var response = { 
 
    "5": { 
 
     "name": "surgeon bueno", 
 
     "country": "Spain", 
 
     "antiquity": "renewal", 
 
     "amount": "2686.97 USD", 
 
     "sellers": { 
 
     "Frank": "2690.58 USD", 
 
     "Bob": "1690.58 USD", 
 
     } 
 
    }, 
 
    "11": { 
 
     "name": "Alex Lloyd", 
 
     "country": "American Samoa", 
 
     "antiquity": "new client", 
 
     "amount": "0.0 USD" 
 
    }, 
 
    "12": { 
 
     "name": "alex lloyd", 
 
     "country": "Aruba", 
 
     "antiquity": "new client", 
 
     "amount": "0.0 USD" 
 
    } 
 
    }; 
 

 
    for (var i in response) { 
 
    $('#modal-table tbody').append("<tr class='grey'><td>" + response[i].name + "</td><td>" + response[i].country + "</td><td>" + response[i].antiquity + "</td><td>" + response[i].amount + "</td>"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<table id="modal-table"> 
 
    <tbody></tbody> 
 
</table>