简体   繁体   中英

Remove an key value from an object in react js

I have an object in the state ,

this.state = {
   selectedValue: {}
}

Now,Here I am adding a property to this by object in the following way

if (e.currentTarget.checked) {
      this.setState({
        selectedType: {
          ...this.state.selectedType,
          [resumeId]: type
        }
      })

Now, In else part I have to remove the property with the matching resumeId .

Or Do I need to create an array of objects ? I am kind of confused here.

Can any one help me with this ?

The best way to do this is add a prefix to your resumId :

if (e.currentTarget.checked) {
      this.setState({
        selectedType: {
          ...this.state.selectedType,
          [`resume-${resumeId}`]: type
        }
      })

Now, you have a way to identify your resumeId. Then loop through your selectedType state and remove resumeId . You can do it as the following:

let selectedType = this.state.selectedType;
for (let key in selectedType) {
  if (key.indexOf('resume') !== -1) {
    delete selectedType[key]
  }
}
this.setState({selectedType})

 if (e.currentTarget.checked) { this.setState({ selectedType: { ...this.state.selectedType, [resumeId]: type } }) else { const selectedType = { ...this.state.selectedType } delete selectedType[resumeId]; this.setState({ selectedType }); } 

You can delete the resumeId from the object iself.

Use Object destructuring to acheive this cleanly:

if (e.currentTarget.checked) {
      this.setState({
        selectedType: {
          ...this.state.selectedType,
          [resumeId]: type
        }
      })
} else {
    // Destructure the resumeId and rest properties
    const { resumeId, ...rest} = this.setState.selectedType;

    // Only assign the rest properties now
    this.setState({ selectedType: ...rest });
}

Update:

To check if all values are same:

 const data = { "a": "11", "b": "11", "c":"12", "d" : "11" }; const objectValues = Object.values(data); // Check first value with every value const isEveryValueSame = objectValues.every(x => x === objectValues[0]); console.log(isEveryValueSame); 

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