You can get the keys with the following function (which is safe to use in older browsers)...
var getObjectKeys = function(obj) {
if (Object.keys && typeof Object.keys == "function") {
return Object.keys(obj);
}
var prop, keys = [];
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
keys.push(prop);
}
}
return keys;
}
jsFiddle.
Alternatively, use Object.keys()
and use an equivalent [shim][2]
for older browsers.
You can check the length
property of the returned Array
to determine the amount of keys.
If you want to dredge up all enumerable properties on the prototype chain, you can use...
var getObjectKeysIncludingInherited = function(obj) {
var keys = [],
i = 0;
for (keys[i++] in obj);
return keys;
}
jsFiddle.
Alternatively, you may really want to use the length
property of an object to do it, but please don't. It's considered somewhat dangerous to augment native JavaScript objects, and it's kind of confusing (Object
s don't have a length
property but Array
s do) and it won't work in older browsers...
Object.defineProperty(Object.prototype, "length", {
get: function() {
return Object.keys(this).length;
}
});
jsFiddle.