当键引用是动态的时,是否有一个使用解构和扩展操作符的ES6 (及更高版本)解决方案来创建一个新对象,其中删除了从原始对象中删除的键和值,因此:
const state = {
12344: {
url: 'http://some-url.com',
id: '12344'
},
12345: {
url: 'http://some-other-url.com',
id: '12345'
}
}
const idToDelete = 12344
const { [idToDelete], ...newState } = state // dynamic key
console.log('newState:', newState)
// desired newState would only have the key 12345 and its value除非是我现在的Babel设置,否则我不能想出干净的ES6方法来做这件事(如果它存在的话)。
非常感谢你提前
发布于 2018-09-04 20:40:28
当使用动态id进行解构时,需要设置一个带有remove值的var: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)
发布于 2018-09-04 20:53:14
我不认为用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);
https://stackoverflow.com/questions/52166519
复制相似问题