0

I have a Json with multiple keys that can change, something like this:

Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]

And I want a table with the headers (num, name, phone)

How can I do it with only JavaScript? (No JQuery)

2
  • 1
    Hello, you may want to review the FAQ "How do I ask a good question?". To increase the chances of answers, you should be as specific as possible and provide problematic code that prevents you from working on further. Good luck! Commented May 26, 2015 at 17:02
  • [duplicate] See stackoverflow.com/q/34888859/14264568 Commented Jun 6, 2021 at 16:37

4 Answers 4

9

var children = [{num: 6, name: 'me', phone: 7}, {num: 8, name: 'him', phone: 9}];

function addHeaders(table, keys) {
  var row = table.insertRow();
  for( var i = 0; i < keys.length; i++ ) {
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(keys[i]));
  }
}

var table = document.createElement('table');
for( var i = 0; i < children.length; i++ ) {

  var child = children[i];
  if(i === 0 ) {
    addHeaders(table, Object.keys(child));
  }
  var row = table.insertRow();
  Object.keys(child).forEach(function(k) {
    console.log(k);
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(child[k]));
  })
}

document.getElementById('container').appendChild(table);
<div id="container"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

The below method will draw a table based on json. First Copy the javascript and html

javascript

<script type="text/javascript">
function jsonToTable(json) {
  var parsejson=JSON.parse(json);
  var columns=[];
  var tablethread="<thead><tr>";
  for (x in parsejson[0]) {
    columns.push(x);
    tablethread+="<th>"+x+"</th>";
  }
  tablethread+="</tr></thead>";
  document.getElementById("tableID").innerHTML=tablethread;
  var table_rows='<tbody>';
  for (var i = 0; i < parsejson.length; i++) {
    var x= parsejson[i];
      var json2=x;
      var row="<tr>"
        for (d in x) {
          var sty=x[d];
          if (sty!=null) {
            var st=sty.toString();
            var reps='<\\';    
            row+="<td><p>"+st.split('<').join('&lt;')+"</p></td>";
          }
          else {
            row+="<td><p>null</p></td>";
          }
        }
      row+="</tr>"
      table_rows+=row;
  }
  table_rows+='</tbody>';
  document.getElementById("tableID").innerHTML+=table_rows;
}
</script>

HTML

<table id="tableID" class="table"></table>

Now Call Method

jsonToTable("YOUR_JSON");

Example

var jsonstring = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';

jsonToTable(jsonstring);

Comments

2
fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => createTable(data)).catch(error=>console.log(error))

const createTable = (data) => {
  const tableData = data;
  
  const headerData = Object.keys(tableData[0]);
  
  const table = document.createElement('table');
  
  const tr = table.insertRow(-1);
 
  
  for(let i=0; i<headerData.length; i++){
    const th = document.createElement('th');
    th.innerHTML = headerData[i];
    tr.appendChild(th)
  }
  
  for(let i=0; i<tableData.length; i++){
    const tr = table.insertRow(-1);
        const obj = tableData[i];
    for(let key in obj) {
        const td = document.createElement('td');
      td.innerHTML = obj[key];
      tr.appendChild(td);
    }
}
  
  document.body.appendChild(table);
}

Comments

0

Javascript

var _table_ = document.createElement('table'),
    _tr_ = document.createElement('tr'),
    _th_ = document.createElement('th'),
    _td_ = document.createElement('td');

// Builds the HTML Table out of myList json data from Ivy restful service.
 function buildHtmlTable(arr) {
     var table = _table_.cloneNode(false),
         columns = addAllColumnHeaders(arr, table);
     for (var i=0, maxi=arr.length; i < maxi; ++i) {
         var tr = _tr_.cloneNode(false);
         for (var j=0, maxj=columns.length; j < maxj ; ++j) {
             var td = _td_.cloneNode(false);
                 cellValue = arr[i][columns[j]];
             td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
             tr.appendChild(td);
         }
         table.appendChild(tr);
     }
     return table;
 }

 // Adds a header row to the table and returns the set of columns.
 // Need to do union of keys from all records as some records may not contain
 // all records
 function addAllColumnHeaders(arr, table)
 {
     var columnSet = [],
         tr = _tr_.cloneNode(false);
     for (var i=0, l=arr.length; i < l; i++) {
         for (var key in arr[i]) {
             if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
                 columnSet.push(key);
                 var th = _th_.cloneNode(false);
                 th.appendChild(document.createTextNode(key));
                 tr.appendChild(th);
             }
         }
     }
     table.appendChild(tr);
     return columnSet;
 }


document.body.appendChild(buildHtmlTable([
    {"num" : "6", "name" : "me", "phone" : "7"},
    {"num" : "8", "name" : "him", "phone" : "9"}
]));

CSS

  th, td {
      border: 1px solid;
  }
  th {
      font-weight : bold
  }

2 Comments

Question explicitly states "No jQuery" (which they shouldn't even have to do, except that people like to pollute every JS question with jQuery nonsense).
Edited my answer to pure JS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.