akaspi
akaspi

Reputation: 275

Querying a javascript array with specific keys

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.

Upvotes: 1

Views: 107

Answers (1)

jonvuri
jonvuri

Reputation: 5920

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

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

Upvotes: 4

Related Questions