首页 > 解决方案 > 即使使用删除运算符,对象属性也不会被删除

问题描述

我有一个对象数组。我想从中删除一个名为 asid的键。我已使用以下代码将其从对象中删除。

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

但是,id 并没有从中删除。我不确定为什么以及我的代码有什么问题。我尝试使用上述逻辑从同一对象中删除其他几个键,并且效果很好。我面临的唯一问题是id.

我认为这个对象属性是不可配置的。如果是这样,那么我们如何删除它。

有人可以帮我解决这个问题。提前致谢。

标签: javascriptreactjs

解决方案


**

如果您使用的是反应,那么您应该始终使用 setState 来更改状态。

**

解释@Prabu的答案

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

推荐阅读