'Customize HTML Table based on data
I have a table that repeats the same data that needs to be a <th>. How can I do it on javascript/jquery? Please see reference table below:
Table I have:
|GameName | Category | Value|
----------------------------------
|Game 1 | Description 1 | 1,000|
|Game 1 | Description 1 | 2,000|
|Game 2 | Description 1 | 3,000|
|Game 2 | Description 1 | 500 |
|Game 3 | Description 1 | 5,000|
|Game 3 | Description 1 | 100 |
|Game 1 | Description 2 | 100 |
|Game 2 | Description 2 | 300 |
|Game 3 | Description 2 | 200 |
Table must be:
|Descriptions| Game 1 | Game 2 | Game 3|
----------------------------------------
|Description1| 3,000 | 3,500 | 5,100 |
|Description2| 100 | 300 | 200 |
Table data will come from an object (sample data below):
[
{
0: "Game1",
1: "Description1",
2: "1,000"
},
{
0: "Game1",
1: "Description1",
2: "2,000"
},
{
0: "Game2",
1: "Description1",
2: "3,000"
},
{
0: "Game2",
1: "Description1",
2: "500"
},
{
0: "Game3",
1: "Description1",
2: "5,000"
},
{
0: "Game3",
1: "Description1",
2: "100"
},
{
0: "Game1",
1: "Description2",
2: "100"
},
{
0: "Game2",
1: "Description2",
2: "300"
},
{
0: "Game1",
1: "Description2",
2: "200"
}
]
My actual code:
var data = [
{
0: "Game1",
1: "Description1",
2: "1,000"
},
{
0: "Game1",
1: "Description1",
2: "2,000"
},
{
0: "Game2",
1: "Description1",
2: "3,000"
},
{
0: "Game2",
1: "Description1",
2: "500"
},
{
0: "Game3",
1: "Description1",
2: "5,000"
},
{
0: "Game3",
1: "Description1",
2: "100"
},
{
0: "Game1",
1: "Description2",
2: "100"
},
{
0: "Game2",
1: "Description2",
2: "300"
},
{
0: "Game1",
1: "Description2",
2: "200"
}
];
var html = '';
for(var i=0; i < data.length; i++) {
var data2 = data[i]
html+= '<tr>' +
'<td>' + data2[0] + '</td>' +
'<td>' + data2[1] + '</td>' +
'<td>' + data2[2] + '</td>' +
'</tr>';
}
$("#tbody").html(html);
table, th, td {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="border">
<thead>
<tr>
<th>GameName</th>
<th>Category</th>
<th>Value</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
