我正试图通过我的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"}}]
问题: 当我通过数组循环时,我只得到输出:base,在我的html文件中。
我的问题:我怎样才能掌握内部数组对象?
答案 0 :(得分:0)
我猜你正试图这样做:
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(', '));
答案 1 :(得分:0)
那是因为你使用的是一个不是数组的对象,所以你不能这样做:
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