簡體   English   中英

通過嵌套的JSON數組循環不起作用

[英]json array loop thru nested not working

我試圖通過我的json objetcs的嵌套數組循環。

這是循環:

        $("#test").text("");
        for(var i=0;i<obj.length;i++){
            $("#test").append(obj[i].line_item + ", ");
            for(var j=0;j<obj[i].length;j++){
                $("#test").append(obj[i][j].iid + ", ");
                $("#test").append(obj[i][j].name + ", ");
                $("#test").append(obj[i][j].price + ", ");
                $("#test").append(obj[i][j].lid + ", ");
                $("#test").append(obj[i][j].picture + "<br />");
            }//for for
        }//for

console.log我沒有顯示任何錯誤,當我回顯php腳本時,得到以下輸出:

[{"line_item":"base","0":
{"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
"1":{"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}}]

問題:當我循環遍歷數組時,我在html文件中僅得到輸出:base。

我的問題:如何獲取內部數組對象?

我猜您正在嘗試這樣做:

var a = [];

$.each(obj, function(i, arr) {
    a.push(arr.line_item);
    $.each(arr, function(j, ob) {
        if (typeof ob == 'object') {
            $.each(ob, function(key,value) {
                a.push(value)
            });
        }
    });
});

$("#test").text(a.join(', '));

小提琴

那是因為您使用的是一個對象而不是數組,所以您不能這樣做:

 obj[i].length

一種簡單易用的解決方法是將項目放入數組(示例JSON)中:

[{"line_item":"base", "items": [
{"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
{"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}]}]

並將您的代碼更改為:

$("#test").text("");
for(var i=0;i<obj.length;i++){
  $("#test").append(obj[i].line_item + ", ");
  for(var j=0;j<obj[i]['items'].length;j++){
    var item = obj[i]['items'][j];
    $("#test").append(item.iid + ", ");
    $("#test").append(item.name + ", ");
    $("#test").append(item.price + ", ");
    $("#test").append(item.lid + ", ");
    $("#test").append(item.picture + "<br />");
  }//for for
}//for

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM