I have an array of objects in javascript. The objects contain some properties and look something like this :
{ "Name" : "blabla", "Id": "1" }
Now I have a function which accepts a single parameter that will be the Name property value of the object. The function looks somethings like this :
function CheckForExistance(array, name){
var exist = false;
$.each(array, function(index, value){
if(value.Name == name)
{
exist = true;
return false;
}
});
return exist;
}
I want to know if there is a better way to do this ?
You can use
$.grep()to filter down the array to a match, and return a comparison of the.length.Or native methods are a little nicer IMO, but you’ll need a shim for old browsers.
This one uses
Array.prototype.some, and will exit as soon as a truthy return value is given, and will then returntrue. If no truthy return is found, then it’ll returnfalse.FWIW, you can make your function a little more robust by providing a dynamic property name as well.
Then use it to check any property value.
Or another approach would be to make a function factory that creates functions to be used with iterators.
Then we can just use
.some()directly without needing theCheckForExistancefunction.Or with
$.grep.