Defining an array of anonymous objects in CoffeeScript

Preslav Rachev picture Preslav Rachev · Jan 27, 2012 · Viewed 26.3k times · Source

How do I define an array of anonymous objects in CoffeeScript? Is this possible at all, using the YAML syntax?

I know that having an array of named objects is quite easy:

items:[
   item1:
      name1:value1
   item2:
      name:value2
]

However, it would be a bit trickier, if those two objects had no names

Answer

Michael Hays picture Michael Hays · Dec 27, 2012

Simple -- place a comma by itself in a column lower than that in which you define your objects.

a = [
     nameA1: valueA1
     nameA2: valueA2
     nameA3: valueA3
  ,
     nameB1: valueB1
     nameB2: valueB2
     nameB3: valueB3
]

Will become:

var a;

a = [
  {
    nameA1: valueA1,
    nameA2: valueA2,
    nameA3: valueA3
  }, {
    nameB1: valueB1,
    nameB2: valueB2,
    nameB3: valueB3
  }
];