With the confusion surrounding jQuery 1.6’s changes to .attr() and the addition of .prop(), one of my favorite new features nearly slipped under the radar. The feature I’m referring to is that $.map() now works against plain JavaScript objects in addition to arrays.

$.map() has always been a useful utility method, somewhat mimicking ECMAScript 5’s native Array.map() method. If you’ve been working with JavaScript long, you’re probably already comfortable with passing anonymous function callbacks around anyway, which makes higher order functions like map an intuitive way to write concise, expressive transformation code.

With jQuery 1.6, now you can use the same approach when working with regular JavaScript objects. There are a variety of uses for this, but I want to focus on one real-world usage in this post: extracting an array of the keys contained within a JavaScript object.

Keys to the kingdom (or at least to an object)

The question of how to extract a collection of an object’s keys comes up often. For example, given an object like this one:

An array of its distinct keys would look like this:

That information is useful for a variety of applications, such as building a table header to represent an arbitrary object’s schema. It’s not something you’ll use on a daily basis, but quite helpful when you do find a need for it.

ECMAScript 5 actually exposes an Object.keys property to provide exactly that information. However, ECMAScript 5 is several years away from being cross-browser safe. For example, Object.keys wasn’t implemented in Internet Explorer until version 9. So, that new feature isn’t terribly useful for most real-world development (yet).

Using $.map() to emulate Object.keys

Until we reach the Utopian future of ubiquitous ECMAScript 5 support, jQuery 1.6’s enhanced map utility provides a syntactically sugary avenue for emulating Object.keys across all browsers.

As map applies its callback function to each property in an object, that function is provided different parameters than the item and index that $.map() has provided in the past. When map is used against an object, the callback function is passed each property’s key and value:

Objects or not, $.map does still return an array consisting of each callback’s return value. Now that we know how to reference each object property’s key name during the callback, building an array of an object’s keys is simple:

Nice and easy, isn’t it?

As always with higher order functions like map, there are iterative alternatives. However, those iterative approaches only result in more code to accomplish the same task. Use this functional approach and enjoy!