Hi,
I've an Array ['red', 'green', 'blue']
I want to create a new Hash from this Array, the result should be
{'red':true, 'green':true, 'blue':true}
What is the best way to achieve that goal
I use prototypejs 1.7_rc2
Thanks
Hi,
I've an Array ['red', 'green', 'blue']
I want to create a new Hash from this Array, the result should be
{'red':true, 'green':true, 'blue':true}
What is the best way to achieve that goal
I use prototypejs 1.7_rc2
Thanks
Just iterate over the array:
var obj = {};
for(var i = 0, l = colors.length; i < l; i++) {
obj[colors[i]] = true;
}
I am not sure what you mean with Hash (in this context) but basically everything is an Object in JavaScript.
Update: If you refer to the Hash object in Prototype, then you can do it like shown and in addition:
var hash = new Hash(obj);
You can also create a new Hash object from the beginning:
var hash = new Hash();
for(var i = 0, l = colors.length; i < l; i++) {
hash.set(colors[i], true);
}
I suggest to have a look at the documentation.
Thanks all
here is my solution using prototypejs
and inspired by Felix's answer
var hash = new Hash();
colors.each(function(color) {
hash.set(color, true);
});