当关键引用是动态的时,是否存在使用解构和扩展运算符的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方式(如果存在)。
提前谢谢了
当使用动态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)
我不认为用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);