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:
In order to extract values from the object, we are using the following code:
var values = ExtractValues(jObj);
alert(values);
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.
Tweet
No comments:
Post a Comment