简体   繁体   中英

looping through json data in JavaScript

This is similar to this question , but I thought I'd reword it a bit differently in order to make myself more clear. I have this json coming back from a $.ajax call:

{"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]]}

Q: In JavaScript, how do I parse through it to make a table such as:

<table>
 <thead>
  <tr>
   <th>PersonID</th>
   <th>First Name</th>
   <th>Last Name</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>1001</td>
   <td>Scott</td>
   <td>Wimmer</td>
  </tr>
  <tr>
   <td>1002</td>
   <td>Phillip</td>
   <td>Senn</td>
  </tr>
  <tr>
   <td>1003</td>
   <td>Paul</td>
   <td>Nielsen</td>
  </tr>
 </tbody>
</table>
var yourJson = {"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]];    
var table = '<table>';

table += '<thead><tr><th>' + yourJson.COLUMNS.join('</th><th>') + '</th></tr></thead>';
table += '<tbody>';

for (var i=0;i<yourJson.DATA.length;i++) {
  table += '<tr><td>' + yourJson.DATA[i].join('</td><td>') + '</td></tr>';
};

table += '</tbody>';
table += '</table>';

您可以使用客户端模板引擎(例如jTemplatespure)轻松实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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