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?
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 grep
over an array, so we just need to get a list of keys with Object.keys
:
$.grep(Object.keys(options), function (k) { return options[k].group == 2; })
//=> ["5"]
this is a filter function for filtering both arrays and objects :
function filter(target, func) {
if (target instanceof Array) {
return target.filter(func);
} else {
var result = {};
$.each(Object.keys(target).filter(function (value) {
return func.call(null, target[value]);
}), function (i, value) {
result[value] = target[value];
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With