How to find keys of a hash?

Pat picture Pat · Aug 20, 2008 · Viewed 194.2k times · Source

I know in javascript Objects double as hashes but i have been unable to find a built in function to get the keys

var h = {a:'b',c:'d'};

I want something like

var k = h.keys() ; // k = ['a','c'];

It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?

I keep feeling it must be a simple built in function that I missed but I can't find it!

Answer

Ivan Nevostruev picture Ivan Nevostruev · Aug 3, 2011

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