Check if object already exists in the array by id

Asked

Viewed 1,430 times

1

I’m developing a project, where a user will assemble a list of contracts, searching for Cpf, only if he searches for the same Cpf 2 times, the contract repeats in the list, as I do to check if the contract already exists in the list array and prevent it from being inserted

    $scope.contratos = [];
   $scope.Pesquisar = function(){
   $http.post('php/GetContratosProtocolo.php', {
  'cpf':cpf
   }).success(function(data){
  if(typeof data == 'object'){  
      $scope.contratos.push(data)
  }else{
  showerror('Contrato Não Encontrado')
   }

    }).error(function(data){
  console.log(data)
   })
   }
  • More details.. what contains data[i]?

  • for example... name:Luiz | Cpf: 111.111.111-11| id: 1

  • i’m doing this for, because date can come with 2 objects, so I play the date[0], date[1] inside the array, and I’m doing a push because the user will assemble a list, so as he goes searching for Cpf, he will insert in the list

  • Luiz: This code is insufficient for us to help you :)

  • I’ll try to rephrase my question

4 answers

2

Every time the user searches for the CPF, a connection with the server will be established, even if it is a CPF already searched and this is unnecessary, because this information can be saved on the client side.

What I suggest in the code below is that the CPF is included as index of the array contratos, what makes sense why currently each object within the array contratos refers to a CPF and it is precisely the duplication that you want to avoid:

$scope.contratos = [];
$scope.Pesquisar = function(){
   //verifica se o CPF é um índice do array contratos 
   //e só faz um novo request se o CPF ainda não foi pesquisado.
   if(typeof $scope.contratos[cpf] === 'undefined') {
       $http.post('php/GetContratosProtocolo.php', {
          'cpf':cpf
       })
       .success(function(data){
          if(typeof data == 'object'){  
              //adiciona um novo elemento ao array utilizando o CPF como índice.
              $scope.contratos[cpf] = data;
          }else{
              //adiciona na mesma o CPF no array de contratos, embora o resultado seja `null`, não deixa de ser uma resposta válida.
              $scope.contratos[cpf] = null;
              showerror('Contrato Não Encontrado')
          }
       })
       .error(function(data){
           console.log(data)
       })
   }
};

Then to extract the data from the array contratos just make a forEach:

$scope.contratos.forEach(function(value, key) {
     //key = cpf utilizado como índice
     //...
});

1

Luiz, I suggest using the method contains array to check if the object already exists in the array before giving the push:

$scope.contratos = [];
$scope.Pesquisar = function(){
$http.post('php/GetContratosProtocolo.php', {
  'cpf':cpf
  }).success(function(data){
    if(typeof data == 'object'){  
      if($scope.contratos.contains(data))
      {
        showerror('Contrato Já Registrado')
      }else{
        $scope.contratos.push(data)
      }
    }else{
      showerror('Contrato Não Encontrado')
    }
  }).error(function(data){
    console.log(data)
  })
}

Font: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/contains

Edit: I’m sorry, this feature is still in experiment and does not exist natively. For it to work, it is necessary to run before:

if (![].contains) {
  Object.defineProperty(Array.prototype, 'contains', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(searchElement/*, fromIndex*/) {
      if (this === undefined || this === null) {
        throw new TypeError('Cannot convert this value to object');
      }
      var O = Object(this);
      var len = parseInt(O.length) || 0;
      if (len === 0) { return false; }
      var n = parseInt(arguments[1]) || 0;
      if (n >= len) { return false; }
      var k;
      if (n >= 0) {
        k = n;
      } else {
        k = len + n;
        if (k < 0) k = 0;
      }
      while (k < len) {
        var currentElement = O[k];
        if (searchElement === currentElement ||
            searchElement !== searchElement && currentElement !== currentElement
        ) {
          return true;
        }
        k++;
      }
      return false;
    }
  });
}
  • $Scope.contratos.contains is not a Function you’re making that mistake

  • I noticed this in a test I did now. I edited the answer with more information.

0

A simple way with few changes would be to create a new function to check if the array already has the value and call it in a condition before adding:

function contains(array,value)
{
    var doescontain = false;
    array.forEach(function(element){
        if(element == value)
        {
            doescontain = true;
        }
    },this);
    return doescontain;
}

Putting in your condition would look like this:

if(typeof data == 'object'){  
  if(contains($scope.contratos,data))
  {
    showerror('Contrato Já Registrado')
  }else{
     $scope.contratos.push(data)
  }
}else{
   showerror('Contrato Não Encontrado')
}

0

I was able to solve it this way

      if(typeof data == 'object'){

    for(var i=0; i<data.length; i++){
      var objExiste = $.grep($scope.contratos, function(n, x){
                    return n.idcontrato == data[i].idcontrato;
                  })

                  if(objExiste.length == 0){
                     $scope.contratos.push(data[i])
                   } else {
          console.log('contrato ja inserido')
      }

        }


}else{
  showerror('Contrato Não Encontrado')
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.