views:

3540

answers:

6

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!

+1  A: 

I'm just jumping into javascript but this post may help you.
http://dean.edwards.name/weblog/2006/07/enum/

jms
+1  A: 

This is the best you can do, as far as I know...

var keys = [];
for (var k in h)keys.push(k);
danb
+1  A: 

I believe you can loop through the properties of the object using for/in, so you could do something like this:

function getKeys(h) {
  Array keys = new Array();
  for (var key in h)
    keys.push(key);
  return keys;
}
palmsey
+13  A: 
Object.prototype.keys = function ()
{
  var keys = [];
  for(i in this) if (this.hasOwnProperty(i))
  {
    keys.push(i);
  }
  return keys;
}
Annan
'hasOwnProperty' excludes properties on the prototypes of this object, which is useful to know.
ijw
A: 

Thanks all,

@Annan,

I'll accept your answer because that's how I ended up implementing it but I feel this should have been a built-in function of the language.

Pat
A: 

I wanted to use the top rated answer above

Object.prototype.keys = function () ...

However when using in conjunction with the google maps API v3, google maps is non-functional.

for (var key in h) ...

works well.

Matthew Darwin