繁体   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