There are cleaner ways to do that loop using $.each
. $.each
passes the callback function the index and the element so you could say:
$.each data, (index, e) ->
arrayOfThings.push(e.thing)
$.each
also sets this
(AKA @
in CoffeeScript) to the current element so you can also say:
$.each data, -> arrayOfThings.push(@thing)
and ignore the callback arguments altogether.
Since your $.each
is effectively unwrapping an array, you could use $.map
instead of $.each
to simplify the callback:
arrayOfThings = $.map data, (e) -> e.thing
CoffeeScript functions have an implicit return so -> x
is the same as -> return x
, this is handy for small mapping functions like this.
If you can assume a reasonably sensible JavaScript environment, then you could use the native Array.prototype.map
instead of jQuery's version:
arrayOfThings = data.map (e) -> e.thing
Loops in CoffeeScript are expressions that yield arrays (see Loops and Comprehensions in the docs for details). That means that you can skip $.each
completely and use a for ... in
loop:
a = (e.thing for e in data)
That assumes that data
is an array. If data
is an object with object values then you could use a for ... of
loop:
a = (v.thing for k, v of data)
And if you already have an array and want add new things to it, you could use concat
:
a = a.concat(e.thing for e in data)
or use push
and a CoffeeScript splat:
a.push((e.thing for e in data)...)
You can combine these last two (i.e. concat
and splat/push
) with the $.map
and Array.prototype.map
versions as well.