Skip to content
Advertisement

How to dynamically create a table from a JSON with nested lists using Javascript?

I’m trying to create an HTML table from a JSON file which values can include nested lists.

Example:

JavaScript

My goal is to create an HTML table with a predefined header for the two columns:

  • header_title_1
  • header_title_2

That will never change, and the table should look like this:

table_example

Thanks for your help !

Advertisement

Answer

Using the for...in iterator on the object to get the key. I created a row for each property, then a cell for the key and value. Then if the value isn’t an array, like the entry2 key, we make it an array to iterate through the elements.

Creating a new row for each element in the array and creating a new cell for the items in the array. If it is an array, the value would be converted to a string separated by the comma ‘,’ or it would be set just as it is.

Then we append the elements to the body of the table.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement