Using jQuery, how do I iterate through an array of objects and return the one that meets certain criteria?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the jQuery grep function:
If your condition you want to test for is anything other than a strict equality, then you will have to use some sort of array iteration that executes your custom comparison. You could do it with
.each()or with.grep()depending upon what type of output you want.If you condition was a strict equality, you could use
jQuery.inArray().Obviously, you don’t need jQuery for this as you could just iterate through the array yourself in plain javascript and implement whatever test you wanted. One advantage of using plain javascript is that you can break out of the iteration when you’ve found the result you want.
In regular javascript: