uncoder
uncoder

Reputation: 1886

JQuery selectors for JavaScript objects?

Is there a way to query JavaScript objects with JQuery selectors?

For example, consider an array:

var users = [{id: 0, username: 'Alice'}, {id: 1, username: 'Bob'}, {id: 2, username: 'Cindy'}];

, then the following works fine:

$(users).each(function (index, user) { ... });

I need to be able do something like this:

$(users).find('[username="Bob"]').each(function(index, user){ ... });

, but I could figure out a proper selector string value. Any ideas?

Upvotes: 0

Views: 56

Answers (2)

alex
alex

Reputation: 490647

You could use Underscore to do it, in particular, findWhere().

bobs = _.findWhere(users, { username: "Bob" });

If you must use jQuery, you could use...

bobs = $.grep(users, function(user) { return user.username === "Bob"; });

Or if your platforms support Array.prototype.filter(), use it in the same way you use jQuery's grep().

Also, when iterating over something with jQuery that isn't a jQuery collection, don't use jQuery.prototype.each(), but use jQuery.each().

Upvotes: 3

Gonzalo.-
Gonzalo.-

Reputation: 12682

use Array.prototype.filter, a native javascript function

users.filter(function(user) { return user.username === "Bob"; }) ;

Upvotes: 3

Related Questions