0

I'm trying to build a HTML table with data from a JSON structured array such as:

var myjson = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName": "Jones"}
]; 

I know I can use:

var tbl = "<table>"

            $.each(myjson, function(x, y) {
                tbl += "<tr>";
                  tbl += "<td>firstName</td>";
                  tbl += "<td>lastName</td>";  
                tbl += "</tr>"; 
                tbl += "<tr>";
                  tbl += "<td>" + y.firstName + "</td>";
                  tbl += "<td>" + y.lastName + "</td>";  
                tbl += "</tr>"; 
              });

tbl += "</table>";

but how can I get the same result if I don't know what the column names (firstName, lastName) are called? How can I iterate through the key/values of each object in the JSON structured array?

In each array, the number of elements in each object will be the same

Peter J Quinn
  • 59
  • 1
  • 2
  • 11
  • 3
    [Object.keys()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) Will give you an array of the objects own properties. You could then iterate that. – ste2425 Aug 16 '16 at 08:42
  • Possible duplicate of [best way to get the key of a key/value javascript object](http://stackoverflow.com/questions/6268679/best-way-to-get-the-key-of-a-key-value-javascript-object) – Iceman Aug 16 '16 at 09:02

4 Answers4

2

Use for...in loop.

for(let key in myjson[0]) console.log(key + ' == ' + myjson[0][key]);

Here is how you code should looks like (see also JSFiddle):

var myjson = [{
  "firstName": "John",
  "lastName": "Doe"
}, {
  "firstName": "Anna",
  "lastName": "Smith"
}, {
  "firstName": "Peter",
  "lastName": "Jones"
}];

var keys = [];
for(let key in myjson[0]) keys.push(key);

var tbl = "<table>"

$.each(myjson, function() {
  tbl += "<tr>";
  for(let index in keys) tbl += '<td>' + keys[index] + '</td>';
  tbl += "</tr>";
  tbl += "<tr>";
  for(let index in keys) tbl += '<td>' + arguments[1][keys[index]] + '</td>';
  tbl += "</tr>";
});

tbl += "</table>";

document.body.innerHTML = tbl;
  • Thanks, I tried this but it only gave me a list of the index numbers – Peter J Quinn Aug 16 '16 at 09:00
  • @PeterJQuinn. Did you try it on JSFiddle? It works as you expected, the indexes you get you can use as property names of your object. –  Aug 16 '16 at 09:03
  • Apologies @SoftwareEngineer171, this does show me results, but it creates rows with the keys every other row. I know I didn't specify not to do this and it'd be easy enough to eliminate this anyway. Thanks a lot – Peter J Quinn Aug 16 '16 at 09:31
2

Use Object.keys to get the keys of the object.

Object.keys() method returns an array of strings that represent all the enumerable properties of the given object.

Use index of array to decide header of table

var myjson = [{
  "firstName": "John",
  "lastName": "Doe"
}, {
  "firstName": "Anna",
  "lastName": "Smith"
}, {
  "firstName": "Peter",
  "lastName": "Jones"
}];
var tbl = "<table>";
$.each(myjson, function(x, y) {
  var keys = Object.keys(y);
  if (!x) {
    tbl += "<tr>";
    keys.forEach(function(key) {
      tbl += "<th>" + key + "</th>";
    });
    tbl += "</tr>";
  }
  tbl += "<tr>";
  keys.forEach(function(key) {
    tbl += "<td>" + y[key] + "</td>";
  });
  tbl += "</tr>";
});

tbl += "</table>";
$('body').append(tbl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

You can simply do this

       var tbl = "<table>"
        $.each(myjson, function(x, y) {
            keys = Object.keys(y);
            tbl += "<tr>";
            $.each(keys, function(i,key){
              tbl += "<td>" + key + "</td>";
            }) 
            tbl += "</tr><tr>"; 
            $.each(keys, function(i,key){
              tbl += "<td>" + y[key] + "</td>";
            }) 
            tbl += "</tr>"; 
          });
         tbl += "</table>";

You can further bring down to one loop if you want.

Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

You can try this.. JSFiddle

tbl += "<tr>";
                        for(var i=0;i<Object.keys(myjson[0]).length; i++)
            {                           
                  tbl += "<td>"+Object.keys(myjson[0])[i]+"</td>";                               
             }
            tbl += "</tr>";
Kumar
  • 270
  • 1
  • 4
  • 17