Hash keys / values as array [duplicate]

In ES5 supported (or shimmed) browsers...

var keys = Object.keys(myHash);

var values = keys.map(function(v) { return myHash[v]; });

Shims from MDN...

  • Object.keys

  • Array.prototype.map


var a = {"apples": 3, "oranges": 4, "bananas": 42};    

var array_keys = new Array();
var array_values = new Array();

for (var key in a) {
    array_keys.push(key);
    array_values.push(a[key]);
}

alert(array_keys);
alert(array_values);

The second answer (at the time of writing) gives:

var values = keys.map(function(v) { return myHash[v]; });

But I prefer using jQuery's own $.map:

var values = $.map(myHash, function(v) { return v; });

Since jQuery takes care of cross-browser compatibility. Plus it's shorter :)

At any rate, I always try to be as functional as possible. One-liners are nicers than loops.


Look at the _.keys() and _.values() functions in either Lodash or Underscore.js:

  • Underscore.js _.keys
  • Underscore.js _.values
  • Lodash _.keys
  • Lodash _.values

function getKeys(obj){
    var keys = [];
    for (key in obj) {
        if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
    } 
    return keys;
}