JavaScript and callback: apply an action on each element of a callback input I'm quite new to js. I even don't know how to call this problem: apply an action on each element of a callback input, but the elements are actually an output..

I crash a lot on this situation: I have a nested callback where first I load a json array and then I perform an action on each element of this array.

$.getJSON(DATA_URL+'/groups', function( groups ) {
    groups.forEach( function(g){
        appendDropdownItem(g);
    } );
});


I want to do it in one line. Not because I think one line is cool but because I think that this nested callback only gets the code dirty and affect readability.

In a pythonic approach I imagine somethings like a comprehension:

[appendDropDownItem(g) for g in loadAjax(DATA_URL+'/groups')]


So.. how to make it one liner/more readable?
First you can realize that function(x){return f(x)} == f, so you can reduce one line there:

$.getJSON(DATA_URL +'/groups', function(groups){
  groups.forEach(appendDropdownItem)
})


It is harder to go further with these builtin functions. But if you have a curried forEach, with the arguments in the right order, such as the one in Rambda, or in Essentialjs (shameless plug), then you can reduce it even more:

$.getJSON(DATA_URL +'/groups', forEach(appendDropdownItem))


There you got a one readable one-liner.

You can implement your own curried forEach in any case:

var forEach = function(f) {
  return function(xs) {
    return xs.forEach(f)
  }
}


But these libraries include many other helpers that provide a more functional workflow that leads to these one-liners often by means of currying and composition.