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.

7
  • Those are not "JSON objects", they are just objects. Your problem/question has nothing to do with JSON. Commented Oct 17, 2012 at 0:56
  • possible duplicate of Find object by id in array of javascript objects Commented Oct 17, 2012 at 0:56
  • Correct. My first steps in client side... Commented Oct 17, 2012 at 1:11
  • Is there a reason why you want to do this with jQuery? Commented Oct 17, 2012 at 1: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... Commented Oct 17, 2012 at 1:26

1 Answer 1

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

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

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

1 Comment

Although it's not using .each, I will keep an open mind :) Thanks!

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.