Convert JSON array to an HTML table in jQuery

前端 未结 15 1091
温柔的废话
温柔的废话 2020-11-22 16:33

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 16:44

    One simple way of doing this is:

    var data = [{
      "Total": 34,
      "Version": "1.0.4",
      "Office": "New York"
    }, {
      "Total": 67,
      "Version": "1.1.0",
      "Office": "Paris"
    }];
    
    drawTable(data);
    
    function drawTable(data) {
    
      // Get Table headers and print
      var head = $("")
      $("#DataTable").append(head);
      for (var j = 0; j < Object.keys(data[0]).length; j++) {
        head.append($("" + Object.keys(data[0])[j] + ""));
      }
    
      // Print the content of rows in DataTable
      for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
      }
    
    }
    
    function drawRow(rowData) {
      var row = $("")
      $("#DataTable").append(row);
      row.append($("" + rowData["Total"] + ""));
      row.append($("" + rowData["Version"] + ""));
      row.append($("" + rowData["Office"] + ""));
    }
    table {
      border: 1px solid #666;
      width: 100%;
      text-align: center;
    }
    
    th {
      background: #f8f8f8;
      font-weight: bold;
      padding: 2px;
    }
    
    

提交回复
热议问题