Question

I'm having trouble transforming this from Jquery/Javascript to coffeescript, simply because I am a beginner and I'm finding it hard to grasp. Could someone give me a hand?

    $.each(data, function (index) {
        arrayOfThings.push(data[index].thing);
    });

This is within a function that takes in AJAX 'GET' data.

Was it helpful?

Solution

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.

Demo: http://jsfiddle.net/ambiguous/Jq6Mh/2/

OTHER TIPS

Here's what I would do (though there are some choices you can make as far as brackets and such go.

$.each data, (index) ->
    arrayOfThings.push(data[index].thing)

The biggest difference is the lack of javascript's function(){} syntax, instead using coffeescript's () -> syntax. Also some brackets can be removed (optional) and of course, the semicolons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top