The problem is that your code is stepping over itself. I’ve moved your code to a CodePen for easier debugging:
Most of the magic happens starting at line 20 in the JavaScript. In this forEach
function, you have two separate if
statements. The first just asks if the key is “batters” and does some work accordingly. The next set checks if you’re currently accessing an array, and again does some work for arrays. But this second if
statement has an else
clause, meaning you’re doing work for anything that is not an array. This includes objects like batters
.
If you comment out the if
statement starting on line 23, your output will be exactly the same. This is because both of those if
blocks are being checked every time. If key === "batters"
, the first block will trigger, but when that’s done your program will still march on to the next set. Since obj.batters
isn’t an array, it’s also executing line 41
which sets the tab cell’s text to [object OBJECT]
.
I was able to fix this problem easily simply by changing your JSON structure so that batters
is an array instead of an object.
{
id: "0001",
type: "donut",
name: "Cake",
ppu: 0.55,
batters: [
{ id: "1001", type: "Regular" },
{ id: "1002", type: "Chocolate" },
{ id: "1003", type: "Blueberry" },
{ id: "1004", type: "Devil's Food" }
],
topping: [
{ id: "5001", type: "None" },
{ id: "5002", type: "Glazed" },
{ id: "5005", type: "Sugar" },
{ id: "5007", type: "Powdered Sugar" },
{ id: "5006", type: "Chocolate with Sprinkles" },
{ id: "5003", type: "Chocolate" },
{ id: "5004", type: "Maple" }
]
},
// ...
}
This makes way more sense than having an object with a single key. You can delete the if
block starting on line 23 and it will work.
Hope that helps.