Convert nested JSON data into a html table

Convert nested JSON data into a html table
0.0 0

#1

Everything works fine , except the “batters” column which shows [object Object].
As you can see in the code, I accessed the array within the object and used forEach to loop through each obj in the array to write it out in the cell, but I don’t know why it didn’t work. Any help appreciated!

Here’s a link to my code: https://pastebin.com/gi07y8dM


#2

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.


#3

THank you! That helps alot