You can use $.grep()
to filter down the array to a match, and return a comparison of the .length
.
function CheckForExistance(array, name){
return $.grep(array, function(obj) {
return obj.Name == name;
}).length > 0;
}
Or native methods are a little nicer IMO, but you'll need a shim for old browsers.
function CheckForExistance(array, name){
return array.some(function(obj) {
return obj.Name == name;
});
}
This one uses Array.prototype.some
, and will exit as soon as a truthy return value is given, and will then return true
. If no truthy return is found, then it'll return false
.
FWIW, you can make your function a little more robust by providing a dynamic property name as well.
function CheckForExistance(array, prop, val){
return array.some(function(obj) {
return obj[prop] == val;
});
}
Then use it to check any property value.
var found = CheckForExistance(myArray, "Name", "blabla");
Or another approach would be to make a function factory that creates functions to be used with iterators.
function havePropValue(prop, value) {
return function(obj) {
return obj[prop] == value;
};
}
Then we can just use .some()
directly without needing the CheckForExistance
function.
var found = myArray.some(havePropValue("Name", "blabla"));
Or with $.grep
.
var found = $.grep(myArray, havePropValue("Name", "blabla")).length > 0;