Reputation: 1886
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
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
Reputation: 12682
use Array.prototype.filter, a native javascript function
users.filter(function(user) { return user.username === "Bob"; }) ;
Upvotes: 3