当键引用是动态的时,是否有一个ES6(及更高版本)解决方案使用解构和散布运算符来创建一个新对象,并从原始对象中删除了一个键和值,所以:
{{1}}
除非这是我当前的Babel设置,否则我无法弄清楚执行此操作的干净ES6方法(如果存在)。
非常感谢
答案 0 :(得分:2)
使用动态ID进行销毁时,您需要设置一个带有remove值的变量:the doc about this
const state = {
12344: {
url: 'http://some-url.com',
id: '12344'
},
12345: {
url: 'http://some-other-url.com',
id: '12345'
}
}
const idToDelete = 12344
// the removed object will go to unusedVar
const { [idToDelete]: unusedVar, ...newState } = state // dynamic key
console.log('newState:', newState)
如果您不需要保留已删除的对象,更好的方法是使用关键字delete
const state = {
12344: {
url: 'http://some-url.com',
id: '12344'
},
12345: {
url: 'http://some-other-url.com',
id: '12345'
}
}
const idToDelete = 12344
delete state[idToDelete]
console.log('newState:', state)
答案 1 :(得分:1)
我认为ES6的解构不可能完全实现。由于其他答案包括改变状态,因此请尝试以下方法:
const state = {
12344: {
url: 'http://some-url.com',
id: '12344'
},
12345: {
url: 'http://some-other-url.com',
id: '12345'
}
}
const idToDelete = 12344
const newState = Object.assign({}, state);
delete newState[idToDelete];
console.log('newState:', newState)
console.log('old state:', state);