I’m trying to use grep to filter a Javascript Object like so:
var options = {
5: {
group: "2",
title: "foo"
},
9: {
group: "1",
title: "bar"
}
};
var groups = $.grep(options, function(e){ return e.group == 2 });
I’m getting empty results and I’m guessing it’s got something to do with the non-sequential keys of the enclosing object. Any ideas how to fix this?
Update
I tried a couple of different grep methods, including using
for (key in option)
to grep on option[key] but I couldn’t get his to work. In the end I went a different route as shown here:
var option_ids = new Array();
for (key in option) {
if ( option[key]['group'] == 2 ) option_ids.push(option[key]['id']);
}
You cannot grep over an object and expect a sane result. However, you can
grepover an array, so we just need to get a list of keys withObject.keys: