I cannot find the javascript equivalent of php array_keys()
/ array_values()
For people unfamiliar with php given the following js hash:
var myHash = {"apples": 3, "oranges": 4, "bananas": 42}
How can I get an array of keys, i.e.
["apples", "oranges", "bananas"]
Same question with the values, i.e.
[3, 4, 42]
jQuery can be used.
This question is related to
javascript
hashmap
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);
Don't know if it helps, but the "foreach" goes through all the keys: for (var key in obj1) {...}
Here is a good example of array_keys
from PHP.js library:
function array_keys (input, search_value, argStrict) {
// Return just the keys from the input array, optionally only for the specified search_value
var search = typeof search_value !== 'undefined',
tmp_arr = [],
strict = !!argStrict,
include = true,
key = '';
for (key in input) {
if (input.hasOwnProperty(key)) {
include = true;
if (search) {
if (strict && input[key] !== search_value) {
include = false;
}
else if (input[key] != search_value) {
include = false;
}
}
if (include) {
tmp_arr[tmp_arr.length] = key;
}
}
}
return tmp_arr;
}
The same goes for array_values
(from the same PHP.js library):
function array_values (input) {
// Return just the values from the input array
var tmp_arr = [],
key = '';
for (key in input) {
tmp_arr[tmp_arr.length] = input[key];
}
return tmp_arr;
}
EDIT: Removed unnecessary clauses from the code.
In ES5 supported (or shimmed) browsers...
var keys = Object.keys(myHash);
var values = keys.map(function(v) { return myHash[v]; });
Shims from MDN...
var myHash = {"apples": 3, "oranges": 4, "bananas": 42}
vals=(function(e){a=[];for (var i in e) a.push(e[i]); return a;})(myHash).join(',')
keys=(function(e){a=[];for (var i in e) a.push( i ); return a;})(myHash).join(',')
console.log(vals,keys)
basically
array=(function(e){a=[];for (var i in e) a.push(e[i]); return a;})(HASHHERE)
Here are implementations from phpjs.org:
This is not my code, I'm just pointing you to a useful resource.
function getKeys(obj){
var keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
}
return keys;
}
look at the _.keys() and _.values() functions in either lodash or underscore
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.
Source: Stackoverflow.com