denisjacquemin denisjacquemin - 29 days ago 13
Javascript Question

How do I create a Hash from an Array using the Prototype JavaScript framewor?

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 using Prototype?

Answer

Just iterate over the array and then create the Hash:

var obj  = {};
for(var i = 0, l = colors.length; i < l; i++) {
    obj[colors[i]] = true;
}
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.

Comments