Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom jQuery Selector That Returns Selected Element Properties Like LINQ

The Problem

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);

What is wrong?

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();

What do we/i need?

Selecting specified element properties as array of objects without reiterating over elements - something that called deferred enumeration

Is it possible?

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.

Research result

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.

like image 303
Beygi Avatar asked Oct 15 '25 16:10

Beygi


1 Answers

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();
like image 189
Frédéric Hamidi Avatar answered Oct 18 '25 05:10

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!