Reputation: 1762
I have a array of objects say items
. I want to find item having name
xyz.
Currently, I wrote a for loop
for(var i = 0; i < items.length; i++)
{
if( items[i].name == "xyz" )
{
found = true;
break;
}
}
Is it possible to shorten this loop to one line statement using jquery? something like this:
$.find(items, "name", "xyz");
Upvotes: 0
Views: 125
Reputation: 18233
(function( $ ) {
$.find = function( array, property, key ) {
var found = false;
for(var i = 0; i < array.length; i++)
{
if( array[i][property] == key )
{
found = true;
break;
}
}
return found ? i : -1;
};
})( jQuery );
Usage: $.find(items, "name", "xyz");
Upvotes: 0
Reputation: 1963
Use jQuerys inArray Example
http://api.jquery.com/jQuery.inArray/
might helps you
Upvotes: 0
Reputation: 3642
var arr = ["abc", "xyz" ];
if($.inArray("abc",arr) > 0){
return true;
}
else
return false
this will return the index of "searching string"
if not found, it will return -1.
Upvotes: 0
Reputation: 664206
Use the native some
method:
items.some(function(el) { return el.name == "xyz"; })
With jQuery, you would need to do something like $.grep
and then check the length ($.grep(items, function(el){ return el.name=="xyz"; }).length > 1
) - not an optimal solution. If you want to use a library solution for those browsers that don't support some
(and don't want to use the polyfill), use Underscore's any
.
Upvotes: 0
Reputation: 100175
Something like:
$.grep(yourArray, function(n) {
return n.name == "xyz";
});
Upvotes: 1
Reputation: 382092
You might use
var matchingItems = items.filter(function(v){return v.name=="xyz"});
or using jQuery (for greater compatibility, as like many Array functions, filter or some aren't available on IE8) :
var matchingItems = $.grep(items, function(v){return v.name=="xyz"});
Upvotes: 1