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.
[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.keysfunction to get an array of the keys (property names) in an object. All modern browsers haveObject.keys(including IE9+).The rest of this answer was written in 2011. In today’s world, A) You don’t need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn’t do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn’t have in 2011, either). You’d use a curated polyfill, possibly from
es5-shimor via a transpiler like Babel that can be configured to include polyfills (which may come fromes5-shim).Here’s the rest of the answer from 2011:
Note that older browsers won’t have it. If not, this is one of the ones you can supply yourself:
That uses a
for..inloop (more info here) to loop through all of the property names the object has, and usesObject.prototype.hasOwnPropertyto 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.)