Konrad Viltersten
Konrad Viltersten

Reputation: 39108

How to return a value from $.each(...)?

To intercept a gazillion of close-votes, I can stress that it's not related to, let alone answered by, this thread.

I'm not sure how to return a value from a $.each(...) construction to the outer scope. Suppose that we have an array of JSON objects (or of arrays for that matter).

var output = "";
$.each(array, function (key1, value1) {
  output += "[" + key1 + "] --> ";
  $.each(value1, function (key2, value2) {
    output += key2 + ":" + value2 + " ";
  });
});
console.log(output);

Right now, as the example above illustrates, I'm relying on a predeclared output that I write to from each of the sub-levels of scope. It works. However, I can't stop feeling that it's not the best approach. I'd like to return something, instead of appending it to the semi-global output.

Upvotes: 1

Views: 262

Answers (3)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

The return statement in .each() return whether or not if the loop continue. To have a .each() returning a value, you can use .map() like that :

var output = $.map(array, function(v, i){
    return "[" + i + "] --> " + $.map(v, function(v, i){
        return i+ ':' + v + ' ';        
    }).join();
}).join();

Fiddle : http://jsfiddle.net/stEV6/

But personnaly, I prefer the way you do it: with a varible.

Upvotes: 4

zerkms
zerkms

Reputation: 254916

If you want to use return - try .reduce() instead:

var output = array.reduce(function(p, value1, key1) {
    var nested = value1.reduce(function(p, value2, key2) {
        return [p, key2, ':', value2, ' '].join('');
    }, '');

    return [p, '[', key1, '] --> ', nested].join('');
}, '');
console.log(output);

http://jsfiddle.net/c2chJ/

Upvotes: 4

Yotam Omer
Yotam Omer

Reputation: 15356

You cannot return value from $.each(), if you return true (or any non false) this means continue and if you return false this means break - this happens because $.each() just loops and runs your anonymous function (the return statement runs in your anonymous function and that is the way $.each() was programmed to handle the returned value).

If you really really have to do this wrap it in a function like so:

function myFunction(){
    var output = '';
    $.each(something,function(){
        output += 'some text'
    })
    return output;
}

Upvotes: 2

Related Questions