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?
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.
This functional javascript solution uses Array.prototype.reduce():
['red', 'green', 'blue']
.reduce((hash, elem) => { hash[elem] = true; return hash }, {})
Parameter Details:
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With