简体   繁体   中英

In JavaScript how can I convert multiple arrays into HTML tables and print them when for-looping a JSON object

I have this for loop where I go over a JSON object, if it finds an array I make it so it creates an HTML table with that array so the information is presented in a much more readable format since the arrays it can find may contain a lot of info. If it doesn't find an array, it simply prints the singular key/value pair which is working fine.

for (var x in myObj) {
  if (myObj[x] instanceof Array) {
    var lista = myObj[x];

    var col = [];
    for (var i = 0; i < lista.length; i++) {
      for (var key in lista[i]) {
        if (col.indexOf(key) === -1) {
          col.push(key);
        }
      }
    }

    table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
    var tr = table.insertRow(-1); // TABLE ROW.
    for (var i = 0; i < col.length; i++) {
      var th = document.createElement("th"); // TABLE HEADER.
      th.innerHTML = col[i];
      tr.appendChild(th);
    }

    for (var i = 0; i < lista.length; i++) {
      tr = table.insertRow(-1);

      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        tabCell.innerHTML = lista[i][col[j]];
      }
    }

    var divContainer = document.getElementById("json");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
  } else {
    document.getElementById("json2").innerHTML +=
      "&lt;p>" + "" + "&lt;b>" + x + "&lt;/b>" + ": " + myObj[x];
  }
}

However, my problem with this code is that it is not able to create multiple tables if the object has more than one array. I believe that if it finds more than one array, it replaces the first table it made with the first array it found with the second array it found, so in the end only one array/table is printed. How can I change this code to make it able to create and print multiples tables/arrays?

In looking through your code, it looks like if you remove divContainer.innerHTML = ""; , or move it to before you start the loop, that the code will safety continue to append a new table to the json element for each array property it finds. That line is effectively deleting the previous table each time it loops through.

Depending on your familiarity with Javascript, this code snippet is showing you 2 different ways of adding HTML to the page. One is by directly editing the HTML text using innerHTML , and the other is by creating new HTML elements and appending them as children to existing HTML elements. The code in this snippet spends much of its time building the table element, through method 2, then right before it appends the table, it uses method 1 to remove all HTML from the element represented by the id json , which of course includes any previous tables that were appended.

For similar use case, I solved this problem in this way.
First I created a class for dynamically creating an HTML Table.
Then in a for loop added rows, header and data into it.

It was for my project to get JSON from the server and added to the UI dynamically as a table of MySql data.

here is the project: jsMyAdmin

 "use strict"; function Table() { var njson = 0; var ntable = 0; var nth = 0; var ntr = 0; var ntd = 0; this.init = function () { njson = 0; ntable = 0; nth = 0; ntr = 0; ntd = 0; } this.prepare = function() { var div = document.createElement( 'DIV' ); document.getElementById( 'terminal' ).appendChild( div ); div.classList.add( 'json' ); ++njson; } this.create = function ( tag, class_name, to, text ) { if( text === undefined ) { text = ''; } switch( tag ) { case 'TABLE': var table = document.createElement( tag ); table.border = '0'; document.getElementsByClassName( to )[ njson - 1 ].appendChild( table ); table.classList.add( class_name ); ++ntable; break; case 'TR': var tr = document.createElement( tag ); document.getElementsByClassName( to )[ ntable - 1 ].appendChild( tr ); tr.classList.add( class_name ); ++ntr; break; case 'TH': var th = document.createElement( tag ); document.getElementsByClassName( to )[ ntr - 1 ].appendChild( th ); var contents = document.createTextNode( text ); th.appendChild( contents ); th.classList.add( class_name ); ++nth; break; case 'TD': var table = document.getElementsByClassName( 'table' )[ ntable - 1 ]; table.border = '1'; var td = document.createElement( tag ); var contents = document.createTextNode( text ); td.appendChild( contents ); document.getElementsByClassName( to )[ ntr - 1 ].appendChild( td ); td.classList.add( class_name ); ++ntd; break; } } } const json_table = new Table(); // the rest are just a sample // see the source code for real use case const jsonFile = { "keys": "values", "key-1": "value-1", "key-2": "value-2", "key-3": "value-3", "key-4": "value-4", }; // add div for our table json_table.prepare(); // add table tag with class-name: json json_table.create( 'TABLE', 'table', 'json' ); for( const key in jsonFile ){ if( key === "keys" ){ json_table.create( 'TR', 'tr', 'table' ); json_table.create( 'TH', 'th', 'tr', "keys" ); json_table.create( 'TH', 'th', 'tr', "values" ); } else { json_table.create( 'TR', 'tr', 'table' ); json_table.create( 'TD', 'td', 'tr', key ); json_table.create( 'TD', 'td', 'tr', jsonFile[ key ] ); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h3>dynamic table</h3> <div id="terminal"> </div> </body> </html> 

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