score:-1

use an if statement to check if the object exists.

if(this.state.objectname)
  delete this.state.objectname

score:0

how about toggling the state?

this.setstate(prevstate => ({
  testobject: {
    ...prevstate.testobject,
    someproperty: !prevstate.testobject.someproperty
  }
}))

score:0

you can check it by this way:

if (this.state.testobject.hasownproperty(property_name))
  delete this.state.testobject.property_name
else {
  var testobject = this.state.testobject
  testobject[property_name] = some_value
  this.setstate({testobject: testobject})
}

score:0

this code will delete the testobject key from the state if present.

assuming that obj is the object you want to delete/add.

let newstate = this.state.testobject

if (this.state.testobject.obj) {
    delete newstate["obj"]
} else {
    newobject["obj"] = "value"
}

this.setstate({ testobject: newstate })

if the obj is present in testobject, then it will delete it, else it will insert obj in testobject.

score:0

lets say the object in question is in testobject with key obj and the incoming var is newtestobj.

then we will check

if(this.state.testobject && this.state.testobject.obj) {
   let tempobj = this.state.testobject;
   delete tempobj.obj;
   this.setstate({
      testobject: tempobj
   })
}else {
  this.setstate({
      testobject: {...testobject, obj: newtestobj.obj}
   })
}

Related Query

More Query from same tag