I have json data like this, form a HTML table with dynamic headings. Leave empty item in that box if there is no value.
[
{
"name":"value1",
"email":"[email protected]"
},
{
"id":"123",
"name":"value2",
},
{
"name":"value3",
"email":"[email protected]",
"messsage":"lorem ipsum"
},
{
"name":"value4",
"email":"[email protected]"
}
]
3
Answers
This is an example on how to accept an array of arbitrary objects and just render them on a table by inspecting all of their properties.
Maybe this is an answer trying to address a problem bigger than what was strictly asked anyway it could be interesting to inspect this option.
The main issue with this solution is that, since there’s no guarantee on the fact that all objects in the array will be consistent with their properties, the very first step is navigating the whole array collecting a set of unique property names found and use it to build the table header.
Such array of unique property names will be used also later to build the table rows. Since the list of objects doesn’t hold the order of the property names, they will be listed randomly in the output table.
The way header and rows get built from the
propertyNames
anddata
goes like this:The order of items in the
uniquePropertyNames
will rule how they will be rendered on the output table.The entry point is just:
Where
'#target'
is the selector to fetch the target table to render the data inside.Edit:
I corrected a mistake I did using the variable
data
inside a function and I added the demo option to pass a list of html elements to the rendering procedure. Just to draw a bigger picture.Try this: