0

Possible Duplicate:
How do I enumerate the properties of a javascript object?
Javascript: Getting a Single Property Name

Given a JavaScript object or JSON object such as:

{
  property: "value"
}

How can one get the word property as a string?

Community
  • 1
  • 1
Donald T
  • 10,234
  • 17
  • 63
  • 91
  • 5
    http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object – gr5 Sep 21 '11 at 17:46

4 Answers4

4
var obj = {
    property: "value"
};

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        alert("key = " + key + ", value = " + obj[key]);
    }
}
roberkules
  • 6,557
  • 2
  • 44
  • 52
3
for(var i in obj) alert(i);//the key name
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

One brutal way would be to use .toString on the object and then extract the name. But i'm sure there would be better ways :)

Bakaburg
  • 3,165
  • 4
  • 32
  • 64
0

Use Object.keys()[docs].

var key = Object.keys( my_obj )[ 0 ];  // "property"

It returns an Array of the enumerable keys in that specific object (not its prototype chain).


To support older browsers, include the compatibility shim provided in the MDN docs.

if (!Object.keys) {
    Object.keys = function (o) {
        if (o !== Object(o)) throw new TypeError('Object.keys called on non-object');
        var ret = [],
            p;
        for (p in o) if (Object.prototype.hasOwnProperty.call(o, p)) ret.push(p);
        return ret;
    }
}
user113716
  • 318,772
  • 63
  • 451
  • 440