Check if value exists in array of objects

1

I have an array that is as follows

[
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param" 1,
    "Valor": 79  
  },
  {
    "Param": 2,
    "Valor": 165
  }
]

I would like to know how to check if the number (in Valor ) exists in the array, if it exists, I remove, if it does not exist, I add. I'm doing this by dialing checkbox , if I mark, I add in the array, if I uncheck, I retreat, I'm not using jQuery.

My code to add

this.checkOne.push({
          "Param": check,
          "Valor": id
        })

I tried to remove it as follows

this.checkOne.map(val => {
          if(val.Valor.indexOf(id) != -1){
            alert('Tem')
          }else{
            alert('nao tem')
          }
        })
    
asked by anonymous 21.07.2017 / 19:49

2 answers

6

You've come close, but map is not the most appropriate method because it's meant to transform one array into another. To exclude you will need the index of the element that will be removed, so it is better to use findIndex :

let checkOne = [
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param": 1,
    "Valor": 79  
  },
  {
    "Param": 2,
    "Valor": 165
  }
];

function adicionaOuRemove(id) {
  let index = checkOne.findIndex(val => val.Valor == id);
  if(index < 0) {
      checkOne.push({Param: 0, Valor: id});
  } else {
      checkOne.splice(index, 1);
  }
}

adicionaOuRemove(165); // existe
console.log(checkOne)

adicionaOuRemove(99);  // não existe
console.log(checkOne)
    
21.07.2017 / 19:56
1

A very simple way to achieve the result would be to use a for loop command. in a very simple way you can iterate over all the elements of your array of objects and check with if there is the value in the desired property. I leave a very simple example of the solution.

var arr = [
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param" :1,
    "Valor": 79  
  },
  {
    "Param": 2,
    "Valor": 165
  }
]

function addOuRemoverObj(valor){



var encontrou = false;

for(var index = 0, total =arr.length; index < total; index++){

var obj = arr[index];

if(obj.Valor == valor){
    arr.splice(index,1);
    encontrou = true;
	break;
}

}


if(encontrou == false)
{
   arr.push({"Param":3, "Valor": valor});
   
}


console.log(arr);

}
//remove
addOuRemoverObj(79);

//adiciona
addOuRemoverObj(333);
    
21.07.2017 / 20:55