According to the documentation $.grep
is for use with arrays, coincidentally it also has several clear examples... your JSON object is not an array but an object literal. Ideally instead of this:
{
"1": {"group":"1", "name":"bmw" },
"2": {"group":"1", "name":"audi" },
"3": {"group":"2", "name":"volvo"}
}
Your response should be coming back similar to this:
{
products: [
{"group":"1", "name":"bmw" },
{"group":"1", "name":"audi" },
{"group":"2", "name":"volvo"}
]
}
Then with a little tweaking your example will return the object's you desire in another array - take note of the difference between the ===
and the ==
operators as in your JSON example the group is returned as a string as opposed to a number.
var group1 = $.grep(all.products, function(el, i){
return el.group == 2;
});
If you still wish to work with your original JSON object (which you shouldn't as it's keys seem redundant and somewhat inefficient), then you will have to devise your own method of filtering. For example:
var group1 = {};
$.each(all, function(i, el){
if(el.group == 2) group1[i] = el;
});