2017-05-23 45 views
0


HTML表我如何轉換對象對象的數組轉換成用jQuery或Javascript

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

以下Javascript數組轉換爲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> 

感謝。

+0

你嘗試過這麼遠嗎? – user1859022

+0

你可以在這裏檢查[你的答案](https://stackoverflow.com/questions/10231864/how-to-print-jquery-object-array) –

+0

請參閱詳細文章https://codepedia.info/create-dynamic- html-table-using-jquery/ –

回答

1

試試這個代碼:

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;
<div id="container"> 
 
</div>

2

您可以使用forEach方法執行此操作,該方法接受參數callback提供的功能。

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>') 
 
});
<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>

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; 

希望這個作品

相關問題