Convert JSON array to an HTML table in jQuery

前端 未结 15 1140
温柔的废话
温柔的废话 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:59

    You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!

    //Sample JSON 2D array
    var json = [{
      "Total": "34",
      "Version": "1.0.4",
      "Office": "New York"
    }, {
      "Total": "67",
      "Version": "1.1.0",
      "Office": "Paris"
    }];
    
    // Get Table headers and print
    for (var k = 0; k < Object.keys(json[0]).length; k++) {
      $('#table_head').append('' + Object.keys(json[0])[k] + '');
    }
    
    // Get table body and print
    for (var i = 0; i < Object.keys(json).length; i++) {
      $('#table_content').append('');
      for (var j = 0; j < Object.keys(json[0]).length; j++) {
        $('#table_content').append('' + json[i][Object.keys(json[0])[j]] + '');
      }
      $('#table_content').append('');
    }
    
    

提交回复
热议问题