简体   繁体   中英

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?

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM