Let me explain more:
we know that map function in jQuery acts as .Select() (as in LINQ).
$("tr").map(function() { return $(this).children().first(); }); // returns 20 tds
now the question is how can we have .SelectMany() in jQuery?
$("tr").map(function() { return $(this).children(); }); // returns 10 arrays not 20 tds!
here is my example in action: http://jsfiddle.net/8aLFQ/4/
"l2" should be 8 if we have selectMany.
[NOTE] please don't stick to this example, above code is to just show what I mean by SelectMany() otherwise it's very easy to say $("tr").children();
Hope it's clear enough.
map
will flatten native arrays. Therefore, you can write:
$("tr").map(function() { return $(this).children().get(); })
You need to call .get()
to return a native array rather than a jQuery object.
This will work on regular objects as well.
var nested = [ [1], [2], [3] ];
var flattened = $(nested).map(function() { return this; });
flattened
will equal [1, 2, 3]
.
You want this:
$("tr").map(function() { return $(this).children().get(); });
Live demo: http://jsfiddle.net/8aLFQ/12/
You're going to kick yourself:
$("tr").map(function() { return [ $(this).children() ]; });
It's the simple things in life you treasure. -- Fred Kwan
EDIT: Wow, that will teach me to not to test answers thoroughly.
The manual says that map
flattens arrays, so I assumed that it would flatten an array-like object. Nope, you have to explicit convert it, like so:
$("tr").map(function() { return $.makeArray($(this).children()); });
Things should be as simple as possible, but no simpler. -- Albert Einstein
$.map
expects a value (or an array of values) returned. The jQuery object you are returning is being used as a "value" instead of an "array" (which get flattened)
All you need to do is return the array of DOM elements. jQuery provides a .get()
method that returns a plain array from a selection.
$("tr").map(function() { return $(this).children().get() });
Of course, I understand this is a very contrived example, since $("tr").children()
does the same thing with a lot less function calls.
http://jsfiddle.net/gnarf/8aLFQ/13/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With