从 JavaScript 对象创建 HTML 表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17684201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create HTML table from JavaScript object
提问by Bin Zhu
I am a beginner of JavaScript and want to display an array of objects in HTML.
我是 JavaScript 的初学者,想用 HTML 显示一组对象。
The format of the data is like this:
数据的格式是这样的:
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
我想使用一个包含三列(id、名称、相关性)的列表来显示它们。并且 id 可以从 1 自动增加。
Could anyone tell me how to write a javascript code to display it?
谁能告诉我如何编写 javascript 代码来显示它?
Please give me some materials or examples to learn.
请给我一些材料或例子来学习。
回答by Jeff Noel
Explanation
解释
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
你想要的是用你的 JavaScript 填充 HTML 中的一个表格(或另一个 DOMElement),一旦页面加载并收到你的 JSON 对象,它就会动态执行。
You want to loop through the object. The best way to do so would be with a for
loop, and making sure our looping variableremains valid for the length of our object (all its attributes).
您想遍历对象。最好的方法是使用for
循环,并确保我们的循环变量对我们的对象(其所有属性)的长度保持有效。
The best way to get the length of a JSON object is through myJSONObject.length
: You select the keys of myJSONObjectand return their count.
获取 JSON 对象长度的最佳方法是myJSONObject.length
:您选择myJSONObject的键并返回它们的计数。
You can access the values stored in your JSON Object the following way, in your for
loop (assuming the looping variable defined is named i
): myJSONObject[i].theAttributeIWantToGet
您可以在for
循环中通过以下方式访问存储在 JSON 对象中的值(假设定义的循环变量名为i
):myJSONObject[i].theAttributeIWantToGet
Price formatting breakdown
价格格式细分
Now, those prices need to have a proper format, don't they? So we'll check if any of the value
attribute has less than 2characters after the .
within them. If they do, we add another decimal 0
. We also add a $
before writing the formatted value. Here is a breakdown of how it works:
现在,这些价格需要有适当的格式,不是吗?因此,我们将检查是否有任何value
属性在其中之后少于 2 个字符.
。如果他们这样做,我们添加另一个小数0
。我们还在$
写入格式化值之前添加了一个。以下是其工作原理的细分:
obj[i].value.toString().substring(startIndex, length)
- We want to check the length after the
.
sign, so our startIndex will be the position of this dot within our string. obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
- We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
Final result:
obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2
- This will return true or false. If it's true: There's less than 2 digits after the dot !
We add the
if
statement and the last zero:if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";
- We want to check the length after the
obj[i].value.toString().substring(startIndex, length)
- 我们想检查
.
符号后面的长度,所以我们的 startIndex 将是这个点在我们的字符串中的位置。 obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
- 我们现在需要设置长度。我们想要找到点之后的所有内容的长度,因此为了安全起见,我们将取整个字符串的长度。
最后结果:
obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2
- 这将返回真或假。如果是真的:点后少于 2 位数字!
我们添加
if
语句和最后一个零:if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";
- 我们想检查
Also:Why I use innerHTML
instead of appendChild()
.
另外:为什么我使用innerHTML
而不是appendChild()
.
Solution
解决方案
JSFiddle
JSFiddle
HTML
HTML
<table>
<tbody id="tbody"></tbody>
</table>
JSON
JSON
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
JavaScript
JavaScript
Note:The JSON object will be named obj
in this instance.
注意:JSON 对象将obj
在此实例中命名。
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
JSFiddle
JSFiddle
回答by Kapil Chhabra
It can be simply done by a small & smart process:
它可以通过一个小而智能的过程简单地完成:
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
回答by Vivin Paliath
You can do something like this:
你可以这样做:
var table = document.createElement("table");
//Add a header
var header = document.createElement("tr");
var idHeaderCell = document.createElement("th");
var nameHeaderCell = document.createElement("th");
var relevanceHeaderCell = document.createElement("th");
header.appendChild(idHeaderCell);
header.appendChild(nameHeaderCell);
header.appendChild(relevanceHeaderCell);
table.appendChild(header);
//Add the rest of the data to the table
for(var i = 0; i < data.length; i++) {
var id = (i + 1);
var name = data[i].key;
var relevance = data[i].value;
var tr = document.createElement("tr");
var idCell = document.createElement("td");
var nameCell = document.createElement("td");
var relevanceCell = document.createElement("td");
idCell.appendChild(document.createTextNode(id));
nameCell.appendChild(document.createTextNode(name));
relevanceCell.appendChild(document.createTextNode(relevance));
tr.appendChild(idCell);
tr.appendChild(nameCell);
tr.appendChild(relevanceCell);
table.appendChild(tr);
}
回答by cesarve
Here a function for build a table from any collection (array of objects)
这里有一个用于从任何集合(对象数组)构建表的函数
const data=[
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active",
testing: 'Gooo!!'
}
]
const createTable=function(data){
const table = document.createElement("table");
const header = document.createElement("tr");
const keys=Object.keys(data[0])
console.log(keys)
for(const key of keys){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key));
header.appendChild(th);
}
table.appendChild(header);
const len=data.length
for(const row of data) {
const tr = document.createElement("tr");
for(const key of keys){
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
delete row[key]
}
/****
you can omit next cycle if all object have the same structor or if the first element of collection have all fields
****/
for(const key in row){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key))
keys.push(key)
header.appendChild(th);
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table
}
}
回答by msweeney
Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:
Array.map() 结合模板文字对于在 JavaScript 中以可扩展的方式为大型对象呈现 HTML 标记非常方便:
function tableMarkupFromObjectArray(obj) {
let headers = `
<th>Index</th>
${Object.keys(obj[0]).map((col) =>`
<th>${col}</th>`
).join('')}`
let content = obj.map((row, idx) => `
<tr>
<td>${idx}</td>
${Object.values(row).map((datum) => `
<td>${datum}</td>`
).join('')}
</tr>
`).join('')
let tablemarkup = `
<table>
${headers}
${content}
</table>
`
return tablemarkup
}
let myobj =[
{ "name": "apple", "rel": 1.90 },
{ "name": "berry", "rel": 1.7 },
{ "name": "banana", "rel": 1.5 },
{ "name": "cherry", "rel": 1.2 }
]
document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
回答by Lochemage
Iterate through the list and retrieve the data for each item this way (assuming your data is in a var called data):
遍历列表并以这种方式检索每个项目的数据(假设您的数据位于名为 data 的 var 中):
for (var i = 0; i < data.length; i++) {
var id = i + 1;
var name = data[i].key;
var relevance = data[i].value;
}
Then, do something with the variables in each loop, print them out however you want.
然后,对每个循环中的变量做一些事情,根据需要将它们打印出来。
回答by Jordan Papaleo
I am not totally sure what you are asking for. The title of you post seems like you are looking for JSON.stringfy like mentioned in the previous answer but apparently you are not.
我不完全确定你在要求什么。您帖子的标题似乎您正在寻找 JSON.stringfy ,就像上一个答案中提到的那样,但显然您不是。
Are you trying to create and HTML list, ? Can you please try to explain your need again? I doubt what you are trying to do is complicated and I sure we can help you if you give a little more detail and purpose of what you are trying to do.
您是否正在尝试创建 HTML 列表?你能再试着解释一下你的需求吗?我怀疑您尝试做的事情很复杂,如果您提供更多细节和目的,我们可以帮助您。
I am going to guess that you are trying to display HMTL by looping over you JSON object. Try this pure JavaScript example:
我猜你想通过循环你的 JSON 对象来显示 HMTL。试试这个纯 JavaScript 示例:
var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]');
var tbl = document.createElement('table');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody")
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_price = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_price.textContent = "Price";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_price);
thead.appendChild(tr_head);
for(var i = 0, j = fruits.length; i < j; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_value = document.createElement("td");
td_id.textContent = i;
td_name.textContent = fruits[i].key;
td_value.textContent = fruits[i].value;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_value);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
回答by Mario Orlandi
Maybe like this:
也许是这样的:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
如果嵌套结构(对象内的对象)obj2htmltable() 可以递归调用自身:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}