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?
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?
var obj = {
property: "value"
};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
alert("key = " + key + ", value = " + obj[key]);
}
}
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 :)
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;
}
}