简体   繁体   中英

React - check if a object is in state variable

I have a state variable that is a object (called testObject). I store several objects in that state variable. Iam looking for a way to check if a object already exists in that state variable then remove it if true.

so to sum up the dilemma:

  • check if a object is already in testObject
  • If true => delete that object
  • if false => add the object to testObject

    class Connector extends Component {

     constructor(props) { super(props); this.state=({ testObject: {}, }); console.log(this.props); } 

    }

How about toggling the state?

this.setState(prevState => ({
  testObject: {
    ...prevState.testObject,
    someProperty: !prevState.testObject.someProperty
  }
}))

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})
}

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.

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}
   })
}

use an if statement to check if the object exists.

if(this.state.objectName)
  delete this.state.objectName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM