2

How do I create an array of anonymous objects with the least number of characters with coffeescript?

Here's how little I've got it down to (works):

cast:
    [ {name: 'Rob Jr.', character: 'Tony Stark'}
      {name: 'Sam Jackson', character: 'Nick Fury'}
      {name: 'Daniel Craig', character: 'James Bond'} ]

I was hoping to be able to do this:

cast:
    [ name: 'Rob Jr.', character: 'Tony Stark'
      name: 'Sam Jackson', character: 'Nick Fury'
      name: 'Daniel Craig', character: 'James Bond' ]

However I get the error:

SyntaxError: [stdin]:20:9: unexpected :

It gets confused by the first colon it encounters. Is there some coffeescript magic I'm missing?

2 Answers 2

1

You can format it like this:

cast: [
  name: 'Rob Jr.', character: 'Tony Stark'
, 
  name: 'Sam Jackson', character: 'Nick Fury'
, 
  name: 'Daniel Craig', character: 'James Bond' 
]
Sign up to request clarification or add additional context in comments.

Comments

0

Whenever I have a long large list I like to use a csv-style array. I think it also adds to readability. Like this:

rows = [
  ["a", "b", "c"]
  [  1,   2,   3]
  [  4,   5,   6]
]

objects = []

columns = rows.shift()

for r in rows
  o = {}
  for c, i in columns
    o[c] = r[i]
  objects.push(o)

alert(JSON.stringify(objects, null, 2))

I have a the code to convert it into the array of objects form in a function in my reusable library. I bet there is something similar in underscore.

Comments

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.