2

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

3 Answers 3

6

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.