当前位置: 动力学知识库 > 问答 > 编程问答 >

Is there a nice way to get hash as a loop result in coffeescript?

问题描述:

In coffeescript loops are expressions and returns an array. For example, we can do

func = (name) -> name.toUpperCase()

result = (func prop for prop in ['a', 'b'])

and get as a result:

['A','B']

But what if I want to get hash table (object) instead of array?

How to modify the above example to get { a: 'A', b: 'B' } ?

I know, that I can do id like this:

func = (name) -> name.toUpperCase()

result = {}

result[prop] = func prop for prop in ['a', 'b']

result

Too verbose! May be there is a nicer way?

网友答案:

While not as nice as a real object comprehension, you can use Array::reduce for this. For your example in particular, using a "transformer" function such as:

transform = (f) -> (prev, curr) ->
  prev[curr] = f curr
  prev

And your func:

func = (name) -> name.toUpperCase()

You can reduce your array with transform and func like so:

result = ['a', 'b'].reduce transform(func), {}

See Approximating object comprehension one-liners in CoffeeScript using Array.reduce() for a lengthier explanation and more examples.

分享给朋友:
您可能感兴趣的文章:
随机阅读: