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

2

4 Answers 4

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>

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

1 Comment

Exactly what I was after! Thank you!
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;

3 Comments

Thanks, I tried this but it only gave me a list of the index numbers
@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.
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
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.

Comments

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>";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.