【问题标题】:Loop through a Json Array using Javascript使用 Javascript 循环遍历 Json 数组
【发布时间】:2017-05-15 16:26:35
【问题描述】:

这是 Postman 返回的 JSON 格式:

e[{
"OrderID": 10248,
"CustomerID": "VINET",
"ContactName": "Paul Henriot",
"EmployeeID": 5,
"OrderDate": "/Date(836431200000)/",
"RequiredDate": "/Date(838850400000)/",
"ShippedDate": "/Date(837468000000)/",
"ShipVia": 3,
"Freight": 32.38,
"ShipName": "Vins et alcools Chevalier",
"ShipAddress": "59 rue de l'Abbaye",
"ShipCity": "Reims",
"ShipRegion": null,
"ShipPostalCode": "51100",
"ShipCountry": "France",
"ProductID": 11,
"ProductName": "Queso Cabrales",
"UnitPrice": 14,
"Quantity": 12,
"Discount": 0},
{
    "OrderID": 10248,
    "CustomerID": "VINET",
    "ContactName": "Paul Henriot",
    "EmployeeID": 5,................

如何使用 Javascript 循环来迭代这个数组,以便为​​每个 ORDER ID 显示产品 ID、产品名称、单价、折扣?我试过这个:

e  function format(d)
{
    var jqxhr = $.getJSON("/Test/GetData", function (jsonResult)
    {
        ParseJson(jsonResult);
    })

    function ParseJson(response)
    {
        var html = "";
        for (var i = 0; i < response.length; i++)
        {
            var id = response[i].OrderID;

            html += "<tr>";
            html += "<td>" + response[i].ProductID + "</td>";
            html += "<td>" + response[i].ProductName + "</td>";
            html += "<td>" + response[i].UnitPrice + "</td>";
            html += "<td>" + response[i].Quantity + "</td>";
            html += "<td>" + response[i].Discount + "</td>";
            html += "</tr>";
        }
        $(document).find("#entrydata").html(html);
    }
    return '<table id = "entrydata" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
  '</table>';
}

但此代码会针对每个订单 ID 返回数据库中的所有产品详细信息。

【问题讨论】:

  • 据我所知,这与 C# 完全无关。

标签: javascript arrays json postman


【解决方案1】:

只需使用 JSON.parse() 从这个 json 中获取 JS 数组,然后使用普通的 JS 循环对其进行迭代。虽然它是一个数组,但您可以使用.forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example

如果你想循环遍历对象,那么你可以使用 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

获取键数组,然后在键数组上使用.forEach

【讨论】:

  • 我一开始就在尝试这样的事情:function format(d) { var x = $.getJSON("/Test/GetData"); var y = JSON.parse(x);但不起作用
  • 过去 3 年没用过 jQuery,不知道哪里出了问题,但我一直在使用 JSON.parse,效果非常好。
猜你喜欢
  • 2013-08-16
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
相关资源
最近更新 更多