The keys of an object is the list of property names. The values of an object is the list of property values. The entries of an object is the list of pairs of property names and corresponding values.
inObject = function(key, value) { if (this. hasOwnProperty(key) && this[key] === value) { return true }; return false; };
There is function in modern JavaScript (ECMAScript 5) called Object.keys
performing this operation:
var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]
Compatibility details can be found here.
On the Mozilla site there is also a snippet for backward compatibility:
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;
}
For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer with shim to ensure Object.keys
in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty
feature.
As of ECMAScript 5 - Object.defineProperty
As of ECMA5 you can use Object.defineProperty()
to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
var keys = [];
for(var i in this) if (this.hasOwnProperty(i)) {
keys.push(i);
}
return keys;
},
enumerable: false
});
var o = {
'a': 1,
'b': 2
}
for (var k in o) {
console.log(k, o[k])
}
console.log(o.keys())
# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]
However, since ECMA5 already added Object.keys
you might as well use:
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
return Object.keys(this);
},
enumerable: false
});
Original answer
Object.prototype.keys = function ()
{
var keys = [];
for(var i in this) if (this.hasOwnProperty(i))
{
keys.push(i);
}
return keys;
}
Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.
There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty
. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.
You can use Object.keys
:
Object.keys(h)
You could use Underscore.js, which is a JavaScript utility library.
_.keys({one : 1, two : 2, three : 3});
// => ["one", "two", "three"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With