简体   繁体   English

从JavaScript中的JSON数组动态生成表

[英]Dynamically generate table from json array in javascript

I have a JSON data as shown below. 我有一个JSON数据,如下所示。 I need to generate a table from this JSON using javascript. 我需要使用javascript从此JSON生成表。 The hardest part for me is to show the each element as a column. 对我而言,最难的部分是将每个元素显示为一列。 Please help me to resolve it. 请帮我解决。

JSON: JSON:

[
 {
   "Header": "Column1",
   "Values": [
     "75",
     "79",
     "83"
   ]
 },
 {
   "Header": "Column2",
   "Values": [
     "77",
     "81",
     "86",
     "90"
   ]
 },
 {
   "Header": "Column3",
   "Values": [
     "98",
     "117"
   ]
 }
]

I want to show this data in below table format 我想以以下表格格式显示此数据

|Column1|Column2|Column3|
-------------------------
| 75 | 77 | 98  |
| 79 | 81 | 117 |
| 83 | 86 |     |
|    | 90 |     |

What will be the best way to achieve it? 最好的方法是什么?

You could get first the headers of the table and while iterating the column names, you could collect the length of every data array and take the max length of it for later iterating the td elements. 您可以首先获取表的标题,并在迭代列名时,可以收集每个数据数组的长度,并获取其最大长度,以便稍后迭代td元素。

 var data = [{ Header: "Column1", Values: ["75", "79", "83"] }, { Header: "Column2", Values: ["77", "81", "86", "90"] }, { Header: "Column3", Values: ["98", "117"] }], table = document.createElement('table'), tr = document.createElement('tr'), rows = [], max = 0, i; table.appendChild(tr); data.forEach(function (o) { var th = document.createElement('th'); th.appendChild(document.createTextNode(o.Header)); tr.appendChild(th); max = Math.max(max, o.Values.length); }); for (i = 0; i < max; i++) { tr = document.createElement('tr'), table.appendChild(tr); data.forEach(function (o) { var td = document.createElement('td'); tr.appendChild(td); td.appendChild(document.createTextNode(i in o.Values ? o.Values[i] : '')); }); } document.body.appendChild(table); 

Loop through your array of objects in order to create the first row (headers) of your table. 循环遍历对象数组以创建表的第一行(标题)。

Then loop again for every row of your table and only access the first element of each Values array everytime. 然后针对表的每一行再次循环,并且每次仅访问每个Values数组的第一个元素。 You can achieve that using var nb = theArray.shift() . 您可以使用var nb = theArray.shift()来实现。 This will remove the first element of the array. 这将删除数组的第一个元素。 So if it returns something, that is what you want to add in your table row, otherwise nothing. 因此,如果它返回某些内容,那就是您想要添加到表行中的内容,否则什么也没有。 When all arrays are empty you are done. 当所有数组都为空时,就完成了。

But keep in mind shift() will remove the value from the array (you call JSON). 但是请记住, shift()将从数组中删除该值(您称为JSON)。 So you might want to perform a copy first (see slice() ). 因此,您可能想先执行复制(请参阅slice() )。

You'll have to use DOM methods and nested for loops to achieve this. 您必须使用DOM方法并嵌套for循环才能实现此目的。

 var tableJSON = [ { "Header": "Column1", "Values": [ "75", "79", "83" ] }, { "Header": "Column2", "Values": [ "77", "81", "86", "90" ] }, { "Header": "Column3", "Values": [ "98", "117" ] } ]; var tableDiv = document.createElement("table"); var trElement = document.createElement("tr"); tableDiv.appendChild( trElement ); var prDiv = document.getElementById("pr"); tableJSON.forEach(function(a_column, index){ if(a_column.Header) { var tdElement = document.createElement("td"); tdElement.innerHTML = "<b>" + a_column.Header + "</b>"; trElement.appendChild( tdElement ); } if(a_column.Values){ var allRows = tableDiv.childNodes; for(var i=0 ;i< a_column.Values.length; i++) { var rowWanted = allRows[i+1]; if( !rowWanted ) { rowWanted = document.createElement("tr"); tableDiv.appendChild( rowWanted ); } if(rowWanted.childNodes.length==0) for(var j=0; j< tableJSON.length; j++){ rowWanted.appendChild( document.createElement("td") ); } rowWanted.childNodes[ index ].innerHTML = a_column.Values[i]; } } }); prDiv.appendChild(tableDiv); 
 <div id="pr"> </div> 

This is how you can start it. 这就是您可以启动它的方式。 1.Iterate through the data and collect the headers, make the HTML for the th here. 1.Iterate通过数据收集头,使这里的的HTML。

2.Iterate through the data and collect the row entries, make the HTML for tr here. 2.遍历数据并收集行条目,在此处创建用于tr的HTML。

Code : 代码:

    var data = [{
        "Header": "Column1",
        "Values": [
            "75",
            "79",
            "83"
        ]
    }, {
        "Header": "Column2",
        "Values": [
            "77",
            "81",
            "86",
            "90"
        ]
    }, {
        "Header": "Column3",
        "Values": [
            "98",
            "117"
        ]
    }];

    var table_headers = "<tr>";
    for(var i=0;i<data.length;i++){
        table_headers = table_headers + "<td>" + data[i].Header + "</td>";
    }
    trs = trs + "</tr>";

    var table = document.createElement('table');
    table.innerHTML = table_headers;

Now you have the headers ready similarly iterate and collect the data and append the entire table to the body of your HTML. 现在,您已经准备好头文件,以同样的方式进行迭代并收集数据,并将整个表追加到HTML正文中。

This is one way I could think of. 这是我能想到的一种方式。 See if this helps. 看看是否有帮助。

Note: Search a bit for similar problems before posting, there may be ideas that could bring you to your solution. 注意:在发布之前先搜索一下类似的问题,可能会有一些想法可以带您进入解决方案。 :) :)

Try this code! 试试这个代码! this will help you to generate output that you need. 这将帮助您生成所需的输出。

<div id="tables">

</div>
<script type="application/javascript"> 

    var jsonStr = '[{"Header": "Column1","Values": ["75","79","83"]},{"Header": "Column2","Values": ["77","81","86","90"]},{"Header": "Column3","Values": ["98","117"]}]';
    var parsJson = JSON.parse(jsonStr);
    var output = '';
    for (var i = 0; i < parsJson.length; i++) {
        output += '<table border="1" style="float:left"><tr><td>' + parsJson[i]['Header'] + '</td></tr>';
        for (var j = 0; j < parsJson[i]['Values'].length; j++) {
            output += '<tr><td>' + parsJson[i]['Values'][j] + '</td></tr>';
        }
        output += '</table>';
        console.log(output);
        document.getElementById('tables').innerHTML = output;
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM