Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash keys / values as array [duplicate]

I cannot find the JavaScript equivalent of PHP array_keys() / array_values().

For people unfamiliar with PHP given the following JavaScript hash:

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

How can I get an array of keys, i.e.,

["apples", "oranges", "bananas"] 

The same question with the values, i.e.,

[3, 4, 42] 

jQuery can be used.

like image 476
greg0ire Avatar asked May 02 '12 13:05

greg0ire


People also ask

Can a hash table have duplicate values?

it can have duplicate values but not keys.

Can array have duplicate keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

Can a hash key have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.


2 Answers

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

like image 53
4 revs, 3 users 75%user1106925 Avatar answered Sep 17 '22 17:09

4 revs, 3 users 75%user1106925


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); 
like image 33
Imp Avatar answered Sep 17 '22 17:09

Imp