使用jQuery或Javascript将对象数组转换为HTML表

时间:2017-05-23 07:02:33

标签: javascript jquery html


如何转换以下对象的Javascript数组

 [{"firstName":"John", "last Name":"Doe", "age":"46"},
 {"firstName":"James", "last Name":"Blanc", "age":"24"}]

进入HTML表格,如下所示

<table>
   <tr>
      <th>firstName</th>
      <th>last Name</th>
      <th>age</th>
   </tr>
   <tr>
      <td>John</td>
      <td>Doe</tD>
      <td>46</th>
   </tr>
   <tr>
      <td>James</td>
      <td>Blanc</tD>
      <td>24</th>
   </tr>
</table>

提前致谢。

4 个答案:

答案 0 :(得分:4)

您可以使用forEach方法执行此操作,该方法接受callback提供的函数作为参数。

&#13;
&#13;
var users=[{"firstName":"John", "last Name":"Doe", "age":"46"},
 {"firstName":"James", "last Name":"Blanc", "age":"24"}]
users.forEach(function(item){
  $('tbody').append('<tr><td>'+item.firstName+'</td><td>'+item["last Name"]+'</td><td>'+item.age+'</td></tr>')
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
</thead>
<tbody>

</tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

试试这段代码:

&#13;
&#13;
var rows = [{"firstName":"John", "last Name":"Doe", "age":"46"},
 {"firstName":"James", "last Name":"Blanc", "age":"24"}];
 var html = '<table>';
 html += '<tr>';
 for( var j in rows[0] ) {
  html += '<th>' + j + '</th>';
 }
 html += '</tr>';
 for( var i = 0; i < rows.length; i++) {
  html += '<tr>';
  for( var j in rows[i] ) {
    html += '<td>' + rows[i][j] + '</td>';
  }
 }
 html += '</table>';
 document.getElementById('container').innerHTML = html;
&#13;
<div id="container">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

在您的HTML下面放置代码

<div id="myTable">

</div>

并在脚本中放下代码

var arrObj = [{"firstName":"John", "lastName":"Doe", "age":"46"},
 {"firstName":"James", "lastName":"Blanc", "age":"24"}]
 var objLength = arrObj.length;
var myvar = '<table>'+
'<tr>'+
'<th>firstName</th>'+
'<th>last Name</th>'+
'<th>age</th>'+
'</tr>';

 for(var i = 0; i < objLength; i++){
myvar += '<tr>'+
'<td>'+arrObj[i].firstName+'</td>'+
'<td>'+arrObj[i].lastName+'</tD>'+
'<td>'+arrObj[i].age+'</th>'+
'</tr>'     
 }

 myvar += '</table>';

console.log(myvar);
 document.getElementById('myTable').innerHTML = myvar;

希望这有效

答案 3 :(得分:-2)

普通JS,在元素中显示“ arrayOfData”的内容:

<pre id="jsarray"></pre>

通过使用以下代码:

document.getElementById("jsarray").textContent = JSON.stringify(arrayOfData, undefined, 2);