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?

1

4 Answers 4

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

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        alert("key = " + key + ", value = " + obj[key]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3
for(var i in obj) alert(i);//the key name

Comments

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 :)

Comments

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;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.