1

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.

Community
  • 1
  • 1
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 1
    you can't return something out of $.each, what you are doing is pretty much the way you have to do it. the only alternative is executing a function with the value inside the each instead. – Kevin B Jun 21 '13 at 00:16
  • @KevinB Dang... Thanks. No room for improvement. I guess my code is perfect. :D – Konrad Viltersten Jun 21 '13 at 00:22
  • use `for` loop and `for..in` :) – sabithpocker Jun 21 '13 at 00:22
  • @sabithpocker How is that going to help? I **definitely** can't return anything from a loop, can I? – Konrad Viltersten Jun 21 '13 at 00:23
  • @KonradViltersten May I suggest changing `array` to `obj`? JS doesn't have key => val (associative) arrays. :) – Matthew Blancarte Jun 21 '13 at 00:25
  • you can definitely `return` from a loop, but returning will return from the `function`. Writing the same thing with `for` and `for..in` makes the idea more clear, and got some performance gains if that matters. – sabithpocker Jun 21 '13 at 00:26
  • 1
    YOu can definitely return from a for loop. However, in your case, you can actually use $.map pretty effectively. – Kevin B Jun 21 '13 at 00:27
  • @sabithpocker I thought that a *return* in a loop would kick me out of the **function** that the loop is in (instead of kicking me out just one level to the outer loop). Perhaps I was mistaken. – Konrad Viltersten Jun 21 '13 at 00:31
  • you are not mistaken `return` will return from the function. breaking out of iterations can be done with `break`, skipping iteration can be done with `continue` – sabithpocker Jun 21 '13 at 00:34

3 Answers3

4

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/

zerkms
  • 249,484
  • 69
  • 436
  • 539
4

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.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
2

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;
}
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65