迭代没有名称的对象键

时间:2016-09-22 10:19:37

标签: jquery json

我有以下对象:

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>");

         });

这是与原始帖子相比的新代码。

1 个答案:

答案 0 :(得分:0)

你可能想要使用vanilla Javascript迭代:

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>");
}

这将迭代对象并将var i设置为每个键。

&#13;
&#13;
$(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>");
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="modal-table">
  <tbody></tbody>
</table>
&#13;
&#13;
&#13;