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?
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?
Share Improve this question edited Nov 19, 2015 at 20:16 Matthew Simoneau 6,2796 gold badges37 silver badges46 bronze badges asked Sep 26, 2010 at 13:22 denisjacquemindenisjacquemin 7,41410 gold badges57 silver badges72 bronze badges3 Answers
Reset to default 17Just 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.
This functional javascript solution uses Array.prototype.reduce():
['red', 'green', 'blue']
.reduce((hash, elem) => { hash[elem] = true; return hash }, {})
Parameter Details:
- callback − Function to execute on each value in the array.
- initialValue − Object to use as the first argument to the first call of the callback.
The third argument to the callback is the index of the current element being processed in the array. So if you wanted to create a lookup table of elements to their index:
['red', 'green', 'blue'].reduce(
(hash, elem, index) => {
hash[elem] = index++;
return hash
}, {});
Returns:
Object {red: 0, green: 1, blue: 2}
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);
});