sprugman sprugman - 6 months ago 13
Javascript Question

best way to get the key of a key/value javascript object

If I have a JS object like:

var foo = { 'bar' : 'baz' }

If I know that
has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it?
for ... in
? I hope there's something better....


If you want to get all keys, ECMAScript 5 introduced Object.keys. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in btw):

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;

Of course if you want both, key and value, then for...in is the only reasonable solution.