首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从JavaScript对象填充超文本标记语言表格?

如何从JavaScript对象填充超文本标记语言表格?
EN

Stack Overflow用户
提问于 2018-06-23 07:11:20
回答 1查看 2.9K关注 0票数 1

我有以下Javascript对象:

data = {
    "Q1": [1,2,3,2],
    "Q2": [5,6,7,6],
    "Q3": [9,10,11,10]
};

由此,我尝试生成以下表格:

+----------+---------+--------+
| Question | Options | Answer |
+----------+---------+--------+
| Q1       |       1 |      2 |
+          +---------+        +
|          |       2 |        |
+          +---------+        +
|          |       3 |        |
+----------+---------+--------+
| Q2       |       5 |      6 |
+          +---------+        +
|          |       6 |        |
+          +---------+        +
|          |       7 |        |
+----------+---------+--------+
| Q3       |       9 |     10 |
+          +---------+        +
|          |      10 |        |
+          +---------+        +
|          |      11 |        |
+----------+---------+--------+

下面是将Javascript对象转换为表的逻辑:字典的键放在列question下,与键对应的值的数组中的前3个值放在列options下,数组中的最后一个值放在列answer下。

例如,对象中的第一个键值对为

"Q1": [1,2,3,2]

Q1位于列Question下,数组[1,2,3,2]中的最后一个值位于列Answer下,数组中的其余三个值成为列Options下的三个单独行。

+----------+---------+--------+
| Question | Options | Answer |
+----------+---------+--------+
| Q1       |       1 |      2 |
+          +---------+        +
|          |       2 |        |
+          +---------+        +
|          |       3 |        |
+----------+---------+--------+

这是我尝试过的:

JSFiddle

下面粘贴了相同的代码片段:

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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-23 08:08:05

以下代码应满足您的要求。

我的解决方案:

  1. 首先循环数据以重塑您的数据,如果需要,您可以添加一些验证器。(似乎数组包括选项和答案,所以假设最后一个总是答案字段),可能有人会觉得这一步不是必要的,但我认为是把它当作一个适配器,对于其他不同格式的数据,我们可以创建另一个适配器来格式化数据,然后不需要修改其余的代码(生成HTML)。然后添加一些验证器将使代码更强大。
  2. 然后循环每个项目以生成行(HTML) (对于Q1,Q2,Q3等),诀窍是使用options.length作为行跨度值。
  3. 组合所有HTML的

data = {
    "Q1": [1,2,3,2],
    "Q2": [5,6,7,6],
    "Q3": [9,10,11,10],
    'Q4': [], // test case 1: no data
    'Q5': [1], // test case 2: only answer field
    'Q6': ['A', 'B', 'C'],// test case 3: for string
    'Q7': ['TEST'] // test case 4: for answer(string) only
};
// For Q4, Q5, you can added some extra codes to uses default values intead, or ignore this row.

// formmat the data first, add some validators if neccessary
function formatAdapter (data) {
  return Object.entries(data).map((item) => {
  let newItem = {}
  newItem[item[0]] = {'options': item[1].slice(0, item[1].length -1),
    'answer': item[-1]} // assuming the last element is the answer, [0:last] is the options
  return [item[0], item[1].slice(0, item[1].length -1), item[1].slice(-1)[0]]
})
}
let formmatedData = formatAdapter(data)

var tbody = document.getElementById('tbody');

// generate the header
tbody.innerHTML += "<tr>" + 
                   "<th id='q'>" + "Question" + "</th>" +
                   "<th id='o'>" + "Options" + "</th>" +
                   "<th id='ca'>" + "Correct Answer" + "</th>" +
                   "</tr>"
// generate the rows(Html) for each questions

let rowHtmls = formmatedData.map((item) => {
  let row = '<tr><td rowspan="'+(item[1].length || 1) +'">'+item[0]+'</td>'
            + '<td>'+item[1][0]+'</td>'
            + '<td rowspan="'+(item[1].length || 1)+'">'+item[2]+'</td></tr>'
  row += item[1].slice(1).reduce((pre, cur) => {
    return pre + '<tr><td>'+cur+'</td></tr>'
  }, '')
  return row
})

// combine header(html) and rows(html)
tbody.innerHTML += rowHtmls.reduce((pre, cur) => {
  return pre+cur
}, '')
table tbody tr td {
  border: 1px solid black
}
<table class="table">
    <tbody id="tbody"></tbody>
</table>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50996553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档