我正在尝试遍历一个多维数组的json数据,但每次循环遍历此数组时,我只会打印出数组的最后一个元素。
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
level_2 = '';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>' +
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>" +
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>" +
'</dl>'
);
$("#content").html(dldata);
}
} else {
console.log('no item for this categories');
}
我上面提到的问题是,在运行代码之后,只有数组中的最后一个元素打印为this fiddle显示。
在小提琴服装,重演剧场和重演&amp;打印了剧院,这是上面每个json数组的最后一个元素。
我的预期输出如下:
Baby & Toddler Clothing
Baby Clothing Accessories
Baby Shoes`
Kids' Clothing, Shoes & Accessories
Boys Clothing [Sizes 4 & Up]
Boys Shoes
Costumes, Reenactment Theater
Costumes
Reenactment & Theater
我预计上面的输出然而我实际得到的只是:
Costumes, Reenactment Theater
Costumes
我希望读者理解我的问题,并提前感谢你的帮助。
答案 0 :(得分:0)
这是因为每次第一个循环运行时都会清除内容div的内容。尝试使用:
$("content").append(dldata);
相反,您应该按预期看到所有三个输出。
答案 1 :(得分:0)
你可以试试这个(我很快就做了,需要重构):
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
firstdata = data[0];
secdata = data[1];
result = '<dl>';
firstdata.map((firstD, i) => {
result += "<dt href='" + firstD.id + "'>" + firstD.name + "</dt>";
secdata[i].map(secD => result += "<dd href='" + secD.id + "'>" + secD.name + "</dd>");
});
result += '</dl>';
console.log(result);
} else {
console.log('no item for this categories');
}
&#13;