1

Consider the following array:

var myArray = [ {"ID":1, "Name":"A"}, {"ID":2, "Name":"B"},
                {"ID":3, "Name":"C"}, {"ID":4, "Name":"D"}];

I would like to use JQuery somehow to query for all JSON objects within the array with respect to some given ID. for example, for the input [{"ID":3}] (I don't know the exact format to pass the parameter so I decided it will be an object within an array however any suggestion will be acceptable) the the result will be only the third object - {"ID":3, "Name":"C"}.
In other words - I would like to "ask" - give me all objects that their 'ID' attribute equals '3'.

I have tried JQuery.each fonction, however, it iterates all over the array and i'm making the "validation check" by myself in my function (given as second parameter after the array). Is there any built in JQuery function / use for this issue?

Thanks,
Amit.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
akaspi
  • 275
  • 1
  • 3
  • 12
  • Those are not "JSON objects", they are just objects. Your problem/question has nothing to do with JSON. – Felix Kling Oct 17 '12 at 00:56
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) – Felix Kling Oct 17 '12 at 00:56
  • Correct. My first steps in client side... – akaspi Oct 17 '12 at 01:11
  • Is there a reason why you want to do this with jQuery? – Ian Oct 17 '12 at 01:19
  • Not something in particular. Just learning this library and thought there is some built in function that do this for me. Probably better than doing it by myself in such early stages in client development for me... – akaspi Oct 17 '12 at 01:26
  • Ahh okay. Well, there is the jQuery `filter` method (like the answer provided), which could be used with `each`. All `each` does is allow you to loop through a matched set of elements or array/object. Depending on how exactly you want to use this, but I'm about to post a basic javascript solution – Ian Oct 17 '12 at 01:50
  • @user1027133: As you can see, the question has been asked before. If you have a look at the question I linked to, you will find how to do it with jQuery's equivalent to `.filter`. – Felix Kling Oct 17 '12 at 02:28

1 Answers1

4
arrayWithJustThrees = myArray.filter(function (object) { return object.ID === 3 })

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

jonvuri
  • 5,738
  • 3
  • 24
  • 32