0

Quick question. I can't find the syntax for it (well assuming it exists) for creating an object from a for loop. What is the correct way to do this -

letters = ['a', 'b', 'c']
objs = (letter[index]:index for letter, index in letters)

#Also tryed..
objs = ({letter[index]:index} for letter, index in letters)

Any ideas?

1
  • 1
    Do you have any libraries? If you had Underscore or Lodash, you could _([e, i] for e, i in letters).object(). Commented Aug 20, 2013 at 23:10

1 Answer 1

2
coffee> letters = ['a', 'b', 'c']
[ 'a', 'b', 'c' ]
coffee> lettersToIndex = {}
{}
coffee> lettersToIndex[letter] = index for letter, index in letters
[ 0, 1, 2 ]
coffee> lettersToIndex
{ a: 0, b: 1, c: 2 }
Sign up to request clarification or add additional context in comments.

2 Comments

Python finally added dict comprehensions: {x: x**2 for x in (2, 4, 6)}. Wonder it that's been suggested for coffeescript?
@hpaulj, yep, many times it seems: #14, #77, #216, and #467. Not a very useful feature when you have _.object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.