views:

40

answers:

2

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

+2  A: 

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.

Felix Kling
Apart from primitives, like strings, numbers, booleans, etc.
Marcel Korpel
@Marcel: I am not quite sure how these are handled internally but I think they are objects too.
Felix Kling
I'm also not sure how JS engines handle those internally, but strings, numbers and booleans are definitely not objects according to the [ECMAScript specification](http://ecma262-5.com/ELS5_Section_8.htm#Section_8). E.g., when using `String` methods, a string primitive is temporarily converted to an object, the method is called and the `String` object is converted back to a string primitive. Also notice that all objects should evaluate to `true`, whereas primitives can evaluate to `false`. E.g.: `var yes = new Boolean(false); if (yes) alert("I <3 JavaScript");` outputs `I <3 JavaScript`
Marcel Korpel
Prototype includes a special object called a Hash.
adamse
@Marcel: I see, ok, thanks for the info. @adamse: Thank you too!
Felix Kling
A: 

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);
});
denisjacquemin