tags:

views:

3541

answers:

2

I was wondering if anyone knows of a way to use the JQuery find method or inArray method to find an item in an array. I can't seem to find anything in the docs.

for example:

var items = [{id:1, name:'bob'}, {id:2, name:'joe'}, {id:3, name:'ben'}];
var found = $(items).find("[name='ben']");

or

var items = [{id:1, name:'bob'}, {id:2, name:'joe'}, {id:3, name:'ben'}];
var found = $.inArray("[name='ben']", items);
+2  A: 

I think what you are looking for is the RichArray plugin and more specifically

$.RichArray.filter()

You can grab it at RichArray

Sarat
Rich Array looks neat.
EndangeredMassa
The in method returns a boolean and i really need the index or preferably the item itself.
bendewey
nor does the in method look much different than the inArray method of the jQuery/Utilities
bendewey
The Filter function worked on the richArray plugin. var filtered = $.richArray.filter(items, function(item) {if (item[attr] == name) { return true; }return false;});if (filtered.length == 0) { return null; }return filtered[0];
bendewey
A: 

The jQuery find method operates on the DOM. If you try to search an array, you'll probably hit this code:

// check to make sure context is a DOM element or a document
if ( context && context.nodeType != 1 && context.nodeType != 9)
    return [ ];

That can be found in the jQuery source for the find method. It always returns an empty array if you are not using a DOM element or the document as your context.

EndangeredMassa