Peter J Quinn Peter J Quinn - 3 months ago 8
JSON Question

Get key/values from JSON array of objects without knowing the key name

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

Answer

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>