Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put multiple items into a JSON object with CoffeeScript?

  categories = {{"code": "zzz", "title": "Electronics"}, {"code": "yyy", "title": "Cars"}};

That's my JavaScript. What's the equivalent CoffeeScript?

like image 990
Shamoon Avatar asked Sep 15 '11 02:09

Shamoon


2 Answers

Braces are optional in CoffeeScript, you can have either this:

categories = [
  code  : 'zzz'
  title : 'Electronics'
,
  code  : 'yyy'
  title : 'Mechanics'
]

(notice the unindented comma) or the more obvious:

categories = [
  {
    code  : 'zzz'
    title : 'Electronics'
  }, // comma optional
  {
    code  : 'yyy'
    title : 'Mechanics'
  }
]
like image 193
Ricardo Tomasi Avatar answered Nov 11 '22 02:11

Ricardo Tomasi


First of all, I think your JavaScript should look like this:

categories = [{"code": "zzz", "title": "Electronics"}, {"code": "yyy", "title": "Cars"}];

You do want an array, correct? Then the CoffeeScript is, well, exactly the same (without the trailing semicolon but that's also optional in JavaScript):

categories = [{"code": "zzz", "title": "Electronics"}, {"code": "yyy", "title": "Cars"}]

There's a "TRY COFFEESCRIPT" button at the top of the Github CoffeeScript page that you might find useful for things like this.

like image 24
mu is too short Avatar answered Nov 11 '22 00:11

mu is too short