I’m attempting to create a search function, built something like this:
function Search(array, key, query, target){
var search_string = new RegExp(query, "i");
var filtered_list = $.grep(array, function (value, index) {
return (value.key.search(search_string) !=-1);
});
$(target).empty();
$.each(filtered_list, printListItem);
}
The problem is with the key and target variables. I’m not sure how to declare them such that they can be used in value.key.search and $(target).empty();. If I declare them as strings, it doesn’t work. For example:
var array = [{'name': 'ben'}, {'name':'kit'}];
var query = $(this).val();
var key = "name";
var target = "div#recipes";
Search(array, key, query, target);
This doesn’t really surprise me… but what I’m wondering is how I should go about abstracting the function, including the key and target values. Thanks!
Use bracket notation.