I do have this sample array of JSON, and I do not know how to loop through them and use it in creating a table row.
Sample code:
var data = [
{foo1:"a",foo2:"b",foo3:"c"},
{foo1:"d",foo2:"e",foo3:"f"},
{foo1:"g",foo2:"h",foo3:"i"}
]
I did use this method:
$.each(data, function (key, value) {
rows += "<tr id=" + key + "><td>" + value.foo1+ "</td><td>" + value.foo2+ "</td><td>" + value.foo3+ "</td><td>"</tr>";
});
//But I want to make it more flexible, so that I can reuse it in making another rows from another array of JSON, like this scenario:
var dataNew = [
{lorem1:"j",lorem2:"k",lorem3:"l"},
{lorem1:"m",lorem2:"n",lorem3:"o"},
{lorem1:"p",lorem2:"q",lorem3:"r"},
{lorem1:"x",lorem2:"s",lorem3:"t"},
{lorem1:"w",lorem2:"y",lorem3:"z"}
]
//Now I cannot use the method above
2
Answers
We can use Object.entries() to get the key and value dynamiclly
You can collect the possible keys that appear in the objects that you have in array. Then iterate over original array of objects and inside iterate over array of keys to get the values and create the rows.
Functional Correctness
Collecting the keys first is required, because JavaScript does not guarantee the order of properties within the object. If you know that each object in the array have the same properties, you may collect keys from the first object only, instead of iterating over all items.
Security
Also, notice that creating DOM elements by concatenating strings is not secure, since this approach is vulnerable to code injections. Assigning values to
.textContent
property of DOM Elements sanitizes the content.