Reputation: 1520
I have Hash obj:
var obj = {a,b,c,...};
obj = $H(obj);
I need to convert it to simple array
[a,b,c,..]
How can I do?
Thx.
Upvotes: 1
Views: 1268
Reputation: 1862
Object.getValues(myObject)
to get an Array of all values.
Object.getKeys(myObject)
to get an Array of keys.
For 1.2 simply, Hash
provides the same methods.
And don't use Objects {}
to store lists like in your example. Arrays
are for lists, Objects
are for associative arrays.
EDIT:
Since version 1.3 Object.getValues
and Object.getKeys
has been deprecated and replaced by Object.keys
resp Object.values
.
Upvotes: 2
Reputation: 26165
since you use $H I am assuming older ver of mootools, 1.2.x since it got deprecated in 1.3 in favour of the new Object. construct
The hash had a .each method:
var Hobj = $H({
tool: "bar",
ghost: "goblin"
});
var arr = [];
Hobj.each(function(value, key) {
arr.push(value); // what to do with key?
});
console.log(arr);
an alternative that grabs the complete objects with their keys but not as array keys:
Hobj.each(function(value, key) {
var obj = {};
obj[key] = value;
arr.push(obj);
});
Upvotes: 2
Reputation: 2964
Assuming you want the values in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(obj[prop]);
}
}
If you want the property names to be in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(prop);
}
}
the hasOwnProperty call is important because it will filter out inherited functions and private members of the mooTools hash class that you don't probably want in your resulting array
Upvotes: 0