Extract Object Values using ECMAScript 5 methods

I find the Object.keys method on ECMAScript 5 extremely useful to return an array containing enumerable properties on a given object. I had a JavaScript object and wanted to extract the values of the object in the shortest possible way. Since my app was targeting the latest browsers, I decided to use Object.keys and the Array.map() method to achieve the task

Here’s how it was done. First, the object is declared as shown here:

EcmaScript Object.Keys

In order to extract values from the object, we are using the following code:

var values = ExtractValues(jObj);

function ExtractValues(o) {
    return Object.keys(o).map(function (objKey) {
        return o[objKey];

As you can see, we are using Object.keys to return an array with properties and then use map which provides a callback function once for each element in an array, and constructs a new array from the results.

Here’s the output


Note: As of this writing, this code will work in IE9, Firefox 4, Safari 5 and Chrome 6-11.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: