Using jQuery, how do I iterate through an array of objects and return the one that meets certain criteria?
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
You can access the properties of an object in JavaScript in 3 ways: Dot property accessor: object.property. Square brackets property access: object['property'] Object destructuring: const { property } = object.
$([1,2,2,4]).filter(function(i,n){return n==2;});
this will return both 2's
basically the array can be an array of dom elements or any array actually, if it is a array returned by a jQuery selector you can do some thing like
$('div.someClass').filter(function(){return $(this).hasClass('someOtherClass')})
just for eg-> this will return all divs which have both someClass and someOtherClass (note: there are other ways to do this)
updating as per your comment, you can do
$(yourArray).filter(function(i,n){return n.Amount && n.Amount == conditionValue;});
You can use the 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 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:
for (var i = 0, len = array.length; i < len; i++) {
if (array[i].Price === 100) {
// match is in array[i]
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With