I have the following Javascript object:
data = {
"Q1": [1,2,3,2],
"Q2": [5,6,7,6],
"Q3": [9,10,11,10]
};
From this I am trying to generate the following Table:
+----------+---------+--------+
| Question | Options | Answer |
+----------+---------+--------+
| Q1 | 1 | 2 |
+ +---------+ +
| | 2 | |
+ +---------+ +
| | 3 | |
+----------+---------+--------+
| Q2 | 5 | 6 |
+ +---------+ +
| | 6 | |
+ +---------+ +
| | 7 | |
+----------+---------+--------+
| Q3 | 9 | 10 |
+ +---------+ +
| | 10 | |
+ +---------+ +
| | 11 | |
+----------+---------+--------+
Here is the logic to converting the Javascript object to the table:
The key of the dictionary goes under column question, the first 3 values in the array of the value corresponding to the key goes under column options, the last value in the array goes under column answer.
For example, the first key value pair in the object is
"Q1": [1,2,3,2]
Q1 goes under column Question and the last value in the array [1,2,3,2] goes under the column Answer, the remaining three values in the array become three individual rows under the column Options.
+----------+---------+--------+
| Question | Options | Answer |
+----------+---------+--------+
| Q1 | 1 | 2 |
+ +---------+ +
| | 2 | |
+ +---------+ +
| | 3 | |
+----------+---------+--------+
Here is what I tried:
Same snippet pasted below:
data = {
"Q1": [1,2,3,2],
"Q2": [5,6,7,6],
"Q3": [9,10,11,10]
};
//console.log(data);
var tbody = document.getElementById('tbody');
tbody.innerHTML += "<tr>" +
"<th id='q'>" + "Question" + "</th>" +
"<th id='o'>" + "Options" + "</th>" +
"<th id='ca'>" + "Correct Answer" + "</th>" +
"</tr>"
for (var question in data) {
var tr = "<tr>";
options = data[question];
answer = options.pop();
tr += "<td rowspan=" + options.length +" headers='q'>" + question + "</td>";
for(var index in options){
tr += "<td headers='o'>" + options[index] + "</td>"
}
tr += "<td headers='ca' rowspan=" + options.length + ">" + answer + "</td>" +
"</tr>"
tbody.innerHTML += tr;
}
<table class="table">
<tbody id="tbody"></tbody>
</table>