user1027167 user1027167 - 1 year ago 94
Javascript Question

get keys of json-object in JavaScript

I have a json-object in JavaScript and I want to get the used keys in it. My JavaScript-Code looks like this:

var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

And I want a loop that alerts me 'person' and 'age', which are the keys of the first object in the json-Array.

Answer Source

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (obj.hasOwnProperty(name)) {
            return keys;

That uses a loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)