简体   繁体   中英

object property is not getting deleted even after using delete operator

I am having an array of objects. And i want to delete one key named as id from it. I have used the following code to delete it from the object.

this.state.result.forEach(item => delete item.id);

But still, id is not getting deleted from it. I am not sure why and what's the issue with my code. I have tried to delete several other keys from same object by using the above logic and it worked fine. Only issue i am facing is with id .

I think this object property is non-configurable. If so, then how can we delete it.

Can someone please help me with this. Thanks in advance.

Maybe id is non-configurable , then you cannot delete it. See this link . Note that a TypeError is thrown in strict mode only.

In React.js you should never try to mutate the state directly. Check out this article from the official docs. You have to use setState() to achieve the results. The id isn't being deleted because re-rendering isn't happening.

From the docs,

Do not modify the state directly

// Wrong
this.state.comment = 'Hello';

Instead, use setState():

// Correct
this.setState({comment: 'Hello'});

In React, you can't directly update the state . You always have to do it using setState method.

So try this.

this.setState({
 result: this.state.result.map(item => {
  let tmpItem = {...item};
  delete tmpItem.id;
  return {...tmpItem}; 
 })
});

Thanks!

**

If you are using the react then you should always use setState for changing the state.

**

To explain @Prabu answer

    this.setState({ // calling setState for updating the state
       result: this.state.result.map(item => {
           let tmpItem = {...item};// storing all the value here in tmpItem
           delete tmpItem.id; // deleting the key
           return {...tmpItem}; // returning here
       })
    }, ()=> {
        // for immediatly accessing the state you can use callback
    });

You should never rely on state :s value when calculating the next state as it may be updated asynchronously by React behind the scenes.

Also, try avoiding delete as it's a performance killer.

So try this instead:

this.setState((state, props) => ({
  result: state.result.map(({id, ...propsToKeep}) => propsToKeep)
}));

or if you have to use delete :

this.setState((state, props) => ({
  result: state.result.map(res => { 
    delete res.id; 
    return res; 
  });
}));

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