views:

44

answers:

3

Hi, I'm using $.grep() to pull back a set of JSON results like so:

myObject.appJSON = jQuery.grep(myObject.appJSON, function (a) { 
        return a.category == "Entertainment"; 
    });

and it works fine. But what I really want to do eventually is have several checkboxes so that that I can filter on several different things. I realize to do that I can just do something like:

myObject.appJSON = jQuery.grep(myObject.appJSON, function (a) { 
        return (a.category == "Entertainment" && a.category == "Business"); 
    });

But my real question here is how to have this happen dynamically, so I can essentially build up a string of features for the grep to return. Maybe I'm showing how novice I am here but it would almost be nice to be able to generate the long filter string then just pop it into the return. It looks like as it is now, the return has to be hard coded. I realize this is probably simple but there's very little out there on the net about how to do this kind of thing. Thanks in advance!

A: 

You can search an array like this:

myObject.appJSON = jQuery.grep(myObject.appJSON, function (a) { 
    return $.inArray(a.category, someArray) > -1;
});
SLaks
Thanks.so basically I just need an array like this and it should work right?var someArray = ['Entertainment'];Because when I do that, it returns an array with a length of 0.
Munzilla
Actually, I think it's just that you have the two things flipped in $.inArray. It should be $.inArray(a.category, someArray) > -1;
Munzilla
@Munzilla: You're right; fixed.
SLaks
A: 

You could use eval() to create your grep logic dynamically. Or you could create a regular expression matching all your categories. But the easiest thing to do is create an object which contains your categories and check if a.category is one of them.

var categories = {
    "Entertainment": 1,
    "Business":      1
};
myObject.appJSON = jQuery.grep(myObject.appJSON, function (a) { 
    return categories[a.category];
});
Schwern
Your syntax is wrong.
SLaks
@SLaks The old "ed" editor used to represent all errors with nothing but a `?`. Your user interface isn't much better.
Schwern
A: 

I think you can regexp the match:

var filter = function(categories) {
    var obj = [];
    $.each(categories.split(' '), function(cat) {
        obj.push(jQuery.grep(myObject.appJSON, function (a) { 
            return cat.test(a.category); 
        }));
    });
    return obj;
}

var filtered_array = filter('Entertainment Business');
David