简体   繁体   中英

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"];

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> 

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM