Reputation: 1598
I have an array of objects, that I would like to add to my table.
I am failing to understand how can I append this data to a table.
var data = [{
id: 12,
data: 70,
mama: "sjk"
}, {
id: 12,
data: "mou",
mama: "sjk"
}, {
id: 12,
data: "mou",
mama: "sjk"
}]
for (var i = 0; i < data.length; i++) {
var node = document.createElement("tr")
var tb = document.createElement("td")
var textnode = document.createTextNode(data[i].data);
tb.appendChild(textnode);
node.appendChild(tb)
document.getElementById("myList1").appendChild(node);
}
<table>
<thead>
<tr>
<th data-field="id">Name</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
<tbody id="myList1">
</tbody>
</table>
Upvotes: 4
Views: 13709
Reputation: 827
The key point is the code in the for-loop create HTML table row element and insert into tbody
.
var node = document.createElement("tr") // <tr></tr>
var tb = document.createElement("td") // <td></td>
var textnode = document.createTextNode(data[i].data);
tb.appendChild(textnode); // insert data into td element <td>data[i].data</td>
node.appendChild(tb) // insert td element into tr <tr><td>data[i].data</td></tr>
document.getElementById("myList1").appendChild(node); // insert tr element into tbody, which is myList1
So after the first loop, the myList1 will be
<tbody id="myList1">
<tr><td>70</td></tr>
</tbody>
after second loop, the myList1 will be
<tbody id="myList1">
<tr><td>70</td></tr>
<tr><td>mou</td></tr>
</tbody>
and so on
Here is what you should do
var data = [{
id: 12,
data: 70,
mama: "sjk"
}, {
id: 12,
data: "mou",
mama: "sjk"
}, {
id: 12,
data: "mou",
mama: "sjk"
}]
for (var i = 0; i < data.length; i++) {
var node = document.createElement("tr")
for (var key of ['id', 'data', 'mama']) {
var tb = document.createElement("td")
tb.innerHTML = data[i][key]
node.appendChild(tb)
}
document.getElementById("myList1").appendChild(node);
}
Upvotes: 3
Reputation: 23396
Since you've tabular data stored into an array of objects, you could first store the property names into an array. Then loop through the data, and on each round, create cells and their content in a nested loop. Something like this:
var row, cell, text, r, c,
prop = ['id', 'data', 'mama'],
table = document.getElementById("myList1");
for (r = 0; r < data.length; r++) {
row = document.createElement('tr');
for (c = 0; c < 3; c++) {
cell = document.createElement('td');
text = document.createTextNode(data[r][prop[c]]);
cell.appendChild(text);
row.appendChild(cell);
}
table.appendChild(row);
}
Upvotes: 3