javascriptjquery

How 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 foo has that basic key/value structure, but don't know the name of the key, How can I get it? for ... in? $.each()?


Solution

  • 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.