JQuery: How to find an object with a specific property equal to a specific value?

Using jQuery, how do I iterate over an array of objects and return one that matches certain criteria?

+8
jquery
source share
3 answers

You can use jQuery grep function:

var matches = jQuery.grep(array, function(item) { // this is a reference to the element in the array // you can do any test on it you want // return true if you want it to be in the resulting matches array // return false if you don't want it to be in the resulting matches array // for example: to find objects with the Amount property set to a certain value return(item.Amount === 100); }); // matches contains all objects that matches if (matches.length) { // first match is in matches[0] } 

If your condition that you want to test is something other than strict equality, then you will have to use some sort of iteration of the array that performs your custom comparison. You can do this with .each() or with .grep() depending on what type of output you want.

If you have strict equality, you can use jQuery.inArray() .

Obviously, you don't need jQuery for this, since you could just iterate over the array yourself in simple javascript and implement any test you need. One of the advantages of using simple javascript is that you can exit the iteration when you find the result you want.

In plain javascript:

 for (var i = 0, len = array.length; i < len; i++) { if (array[i].Price === 100) { // match is in array[i] break; } } 
+14
source share
 $([1,2,2,4]).filter(function(i,n){return n==2;}); 

it will return both

basically the array can be an array of dom elements or any array actually, if it is the array returned by the jQuery selector, you can do something like

 $('div.someClass').filter(function(){return $(this).hasClass('someOtherClass')}) 

just for eg-> this will return all divs that have both someClass and someOtherClass (note: there are other ways to do this)

according to your comment, you can do

 $(yourArray).filter(function(i,n){return n.Amount && n.Amount == conditionValue;}); 
+1
source share

You do not need jQuery to do what you need:

 var objects = [{id:23, amount:232}, {id:42, amount: 3434}, ...] // the function which finds the object you want, pass in a condition function function findObject(objectMeetsCondition){ for(var i = 0 ; i < objects.length ; i++){ if(objectMeetsCondition(objects[i])) return objects[i]; } } // your custom condition that determines whether your object matches function condition(obj){ return obj.amount == 3434; } findObject(condition); // returns {id:42,amount:3434} 
0
source share

All Articles