I have implemented check-boxes on a screen in react native and what I am trying to achieve is that upon selection of checkbox it would add that object to an array and upon unchecking it would remove it from the array.
I have tried using filter method as well as loops but it doesn't work the way it is required.
for (let i = 0; i<tmp.length; i++){
console.log("length",tmp.length)
if(tmp.id == item.id){
tmp.splice(tmp.indexOf(item.id),1);
// tmp.pop(item)
console.log("POP")
}
else {
tmp.push(item);
console.log("PUSH")
}
}
My array of objects is as follows:
contacts:[
{name:'a', id:1, plant:3},
{name:'b', id:2, plant:1},
{name:'c', id:3, plant:1}
],
Code for checkboxes:
<CheckBox
checked={this.state.selectedCheckList.includes(item.id)? true:false}
onPress={()=>this.onCheckboxPress(item)} color={"#8BC63E"}
/>
I expect the array that I am creating in tmp
to be dynamic, in such a way that it removes and adds whole specific objects from the array.
Before:
tmp:[
{name:'a', id:1, plant:3},
{name:'b', id:2, plant:1},
{name:'c', id:3, plant:1}
],
After:
tmp:[
{name:'a', id:1, plant:3},
{name:'c', id:3, plant:1}
],