2016-09-22 45 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- jqueryではない) – guradio

答えて

0

おそらく、バニラJavascriptを使用して反復したい:

​​

これは、オブジェクトを反復処理し、すべてのキーにvar iを設定します。 [オブジェクトが空であるか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>