Reputation:
Given this object: http://kopy.io/H2CqY
I need to check if some card_id already exists in the visitor's array. How do I do so? I tried it with a loop but that didn't work because when I get a new data.card_id and there are already multiple entries in the visitors array it might not match.
My code:
$scope.$on("addMultiVisitor", function(evt, data) {
$scope.newVisit.visitors.length + 1;
$scope.newVisit.visitors.push({
"access_route_id": "",
"card_id": data.id,
"identity_id": data.identity.id,
"company_id": data.company.id,
"company_name": data.company.name,
"firstname": data.identity.given_names,
"lastname": data.identity.surname,
"birthdate": new Date(data.identity.birthdate)
});
window.scrollTo(0, document.body.scrollHeight);
$scope.$apply();
});
Upvotes: 3
Views: 2518
Reputation: 18279
You can check if your object already exist in your array with indexOf()
.
If the object is not in the array, it will return -1:
$scope.o = {
"access_route_id": "",
"card_id": data.id,
"identity_id": data.identity.id,
"company_id": data.company.id,
"company_name": data.company.name,
"firstname": data.identity.given_names,
"lastname": data.identity.surname,
"birthdate": new Date(data.identity.birthdate)
}
if($scope.newVisit.visitors.indexOf(o) == -1) { // Not in the array
$scope.newVisit.visitors.push(o);
}
But I guess @tymeJV answer fits your need better.
Upvotes: 0
Reputation: 104775
You can use the Array.some
method:
var doesIdExist = $scope.newVisit.visitors.some(function(v) {
return v.card_id === data.id;
});
If anything in the array matches the condition, true
will be the result, else false
.
Upvotes: 5