0

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?

1
  • 2
    Array.prototype.filter() Commented Dec 10, 2014 at 0:59

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

... but use Array.prototype.forEach() ;-P
@zerkms Definitely, if your target platforms support it.
Thank you! jQuery.prototype.each() vs. jQuery.each() - could you, please, elaborate why?
The first is made for jQuery collections, the second for any array-like object.
3

use Array.prototype.filter, a native javascript function

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.