.grep on an JSON object
jquery, json
Solution
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"]
Problem
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']); } ```