Check if value exists in object array

Asked

Viewed 9,256 times

2

I have an array which is as follows

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

I would like to know how to verify the number (no Valor) exists in the array, if it exists, I remove, if it does not exist, I add. I’m doing it by scoring one checkbox, if I mark, I add in the array, if I clear, I remove, I am not using jQuery.

My code to add

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

I tried to do the following to withdraw

this.checkOne.map(val => {
          if(val.Valor.indexOf(id) != -1){
            alert('Tem')
          }else{
            alert('nao tem')
          }
        })
  • If it’s a checkbox that will control, not just check whether it is selected or not? Because if it was selected, the element must exist, if it was not, you will enter the value.

2 answers

8


You came close, only the mapis not the most appropriate method, because it was made to transform one array into another. To delete 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)

  • I couldn’t understand the code, could you explain? and also didn’t work here, he adds, but never falls to remove, always gives as if the value did not exist, even after I have added

  • There was an error in my code. I fixed and enlarged the example for you to see working. Which part of the code you did not understand?

  • Now it worked, thanks friend :D

1

A very simple way to achieve the result would be to use a for loop command. Quite simply you can iterate over all the elements of your object array and check with if if there is a 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);

Browser other questions tagged

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