I need some properties of each item that query returns as array of objects
What we do right now
$('selector').each(create array of texts or whatsoever);
Why should we iterate over elements for each requirement?
Here is the same thing in LINQ
IQueryable<Book>;
books.Select(b=> b.Text).ToArray();
// or another sample
books.Select(b=> new { b.Text , b.ISBN}).ToArray();
Selecting specified element properties as array of objects without reiterating over elements - something that called deferred enumeration
I think yes it is, because right now i have some ideas.
I already know about 'map' and 'each' methods, beware that both of them will reiterate over selector items.So yes map will results what i want, but not exactly.
Also note that even C# that have more better performance than java-script is using this method that i'm asking for,
So this is a requirement for all web-developers not just me and that's exactly why i'm sharing the problem here to be solved.
Iteration over elements using jQuery is inevitable because jQuery itself is not finding elements using loop over document elements until that's necessary for example pseudo classes, so for implementing deferred enumeration over jQuery infrastructure we have to force jQuery to iterate over items, and that makes it slow.
I'd implemented deferred enumeration using a pseudo class named 'select' and passing in .net like lambda expression.That was handling selects very nicely just like .net, but result was slower than map and each jQuery methods up to 50%.Finally the answer is jQuery map method.
You might be looking for the map() method:
var books_text = $(".book").map(function() {
return $(this).text();
}).get();
var books_info = $(".book").map(function() {
var $this = $(this);
return {
text: $this.text(),
isbn: $this.attr("isbn") // If stored in an attribute.
};
}).get();
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