Dil85
Dil85

Reputation: 176

Filtering a json object with array of values using jquery grep

I need to filter JSON result using jQuery grep.My JSON result look like this:

 var data = { "items":[
  {
      "Name":           "Name 1",
      "City":      "city1"
  },
  {         
      "Name":           "Name 2",
      "City":      "city2"
  },
  {
      "Name":       "Name 3",
      "City":      "cat1"
  }
]}

Filter this JSON with array of Name example:

var Name= ["Name 1","Name 2"];

Upvotes: 2

Views: 15911

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use jQuery.grep() to filter the items array

var data = {
  "items": [{
    "Name": "Name 1",
    "City": "city1"
  }, {
    "Name": "Name 2",
    "City": "city2"
  }, {
    "Name": "Name 3",
    "City": "cat1"
  }]
}
var name = ["Name 1", "Name 2"];

var res = $.grep(data.items, function(v) {
  return name.indexOf(v.Name) > -1;
});

document.write('<pre>' + JSON.stringify(res, 0, 3) + '</pre>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Or with filter()

var data = {
  "items": [{
    "Name": "Name 1",
    "City": "city1"
  }, {
    "Name": "Name 2",
    "City": "city2"
  }, {
    "Name": "Name 3",
    "City": "cat1"
  }]
}
var name = ["Name 1", "Name 2"];

var res = data.items.filter(function(v) {
  return name.indexOf(v.Name) > -1;
});

document.write('<pre>' + JSON.stringify(res, 0, 3) + '</pre>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 6

Pragnesh Khalas
Pragnesh Khalas

Reputation: 2898

If you need to get the string array from existing object array using $.grep so first use $.grep for filter the object and then use $.map for get the specific output from the result object like below code will help you.

Filter the object using $.grep

var data = {
    "items": [
  {
      "Name": "Name 1",
      "City": "city1"
  },
  {
      "Name": "Name 2",
      "City": "city2"
  },
  {
      "Name": "Name 3",
      "City": "cat1"
  }
    ]
};

var objret = $.grep(data.items, function (n, i) {
    return n.Name == 'Name 1' || n.Name == 'Name 2';
});

Now you have result object in the objret variable now convert the object result to your string array out put using $.map like :-

Get OutPut

var array = $.map(objret, function (value, index) {
    return [value.Name];
});

so in the array have your required output.

Upvotes: 1

Came19xx
Came19xx

Reputation: 72

I think is the same questione exposed here: [question] Filtering a json array using jquery grep

However json array are like string, or you get an array from that or u can access it only like string. Use jquery grep to recreate the array then access it via index to compare value

Upvotes: 0

Related Questions