最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

prototypejs - How do I create a Hash from an Array using the Prototype JavaScript framewor? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 17

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);
});
发布评论

评论列表(0)

  1. 暂无评论