Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.grep on an JSON object

Tags:

json

jquery

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']);
}
like image 779
user1648217 Avatar asked Nov 15 '12 05:11

user1648217


Video Answer


2 Answers

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"]
like image 68
jmdeldin Avatar answered Oct 10 '22 19:10

jmdeldin


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];
    });
  }
}
like image 45
Sajjad Shirazy Avatar answered Oct 10 '22 20:10

Sajjad Shirazy