14 June 2021

Convert javascript object into html table, where keys are in the first column and values are in the second column. This uses plain javascript so you can use it anywhere.

Source code viewer
  1. var objectToTable = {key1: 'value1'};
  2.  
  3. // Create new table element.
  4. var keyValueTable = document.createElement('table');
  5. // Add attribute id, you can also add classes for an example.
  6. keyValueTable.setAttribute('id', 'keyValueTable');
  7. // loop through the javascript object.
  8. for (var key in objectToTable) {
  9. // Create row.
  10. var tr = document.createElement('tr');
  11. keyValueTable.appendChild(tr);
  12.  
  13. // Create first column with value from key.
  14. var td = document.createElement('td');
  15. td.appendChild(document.createTextNode(key));
  16. tr.appendChild(td);
  17.  
  18. // Create second column with value from value.
  19. var td2 = document.createElement('td');
  20. td2.appendChild(document.createTextNode(objectToTable[key]));
  21. tr.appendChild(td2);
  22. }
  23.  
  24. // You can use your generated table anywhere. For an example append it to somewhere with jquery.
  25. $('someDiv').append(keyValueTable);
Programming Language: Javascript