If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOf
or a regular expression to test the strings.
For the loop, you have at least three choices:
A boring old for
loop.
On ES5-enabled environments (or with a shim), Array#filter
.
Because you're using jQuery, jQuery.map
.
Boring old for
loop example:
function search(source, name) {
var results = [];
var index;
var entry;
name = name.toUpperCase();
for (index = 0; index < source.length; ++index) {
entry = source[index];
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
results.push(entry);
}
}
return results;
}
Where you'd call that with obj.list
as source
and the desired name fragment as name
.
Or if there's any chance there are blank entries or entries without names, change the if
to:
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
Array#filter
example:
function search(source, name) {
var results;
name = name.toUpperCase();
results = source.filter(function(entry) {
return entry.name.toUpperCase().indexOf(name) !== -1;
});
return results;
}
And again, if any chance that there are blank entries (e.g., undefined
, as opposed to missing; filter
will skip missing entries), change the inner return to:
return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;
jQuery.map
example (here I'm assuming jQuery
= $
as is usually the case; change $
to jQuery
if you're using noConflict
):
function search(source, name) {
var results;
name = name.toUpperCase();
results = $.map(source, function(entry) {
var match = entry.name.toUpperCase().indexOf(name) !== -1;
return match ? entry : null;
});
return results;
}
(And again, add entry && entry.name &&
in there if necessary.)