I am facing an issue while trying to iterate through a multidimensional json data array. Each time I loop through the array, only the last element gets printed.
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].id;
}
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');
}
After running the code, I noticed that only the last element in the array was printed, as shown in this fiddle.
The fiddle displays Costumes, Reenactment Theater, and Reenactment & Theater which are the last elements of each json array mentioned above.
The expected output should be:
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
However, I only got:
Costumes, Reenactment Theater
Costumes
I hope this clarifies my question and appreciate any help in advance.