Jeova Almeida Jeova Almeida - 1 year ago 82
Javascript Question

Get key names for JSON array for all browser versions

I have a JSON array and i'd like to get their key names.

I searched and found no solution that really solved the problem. So I created my own:

var data = [{ Id: 25 }, {Year: 18} ];

$.each(data, function (i, element) {
var stringfied = JSON.stringify(element);
var parts = stringfied.split('":'); //separate key and value
var key = parts[0].split('{"')[1]; // get key
console.info(key);
console.info(element[key]);
});


I tried other solutions like:

for (var key in data) {
console.info(key);
info(data[key]);
}


but that didn't show the key names.

Is there a better solution? (Object.keys requires modern browsers, doesn't fit)

Answer Source

Imagine what your code will do if one of the keys contains a leading colon.

This will do the job:

var data = [
  {
    Id: 25
  }, 
  {
    Year: 18
  }
];

for (var i = 0; i < data.length; ++i) {
  var element = data[i];

  for (var k in element)
    if (element.hasOwnProperty(k)) {
      console.log(k);
      console.log(element[k]);
    }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download