3

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();
  });
0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But remember about browser support, 'some' is IE >= 9 developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
@PawełKozikowski - True, I hope by this point everyone is developing for >= IE9 by now
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.