[英]ES6 destructuring: How do I create a new object that omits dynamically referenced keys
Is there an ES6 (and upwards) solution using destructuring and the spread operator to create a new object with a key and value deleted from the original object, when the key reference is dynamic, so: 当键引用是动态的时,是否有一个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
Unless it's my present Babel setup, I can't figure out the clean ES6 way of doing this (if it exists). 除非这是我当前的Babel设置,否则我无法弄清楚执行此操作的干净ES6方法(如果存在)。
Many thanks in advance 提前谢谢了
when destructuring using dynamic id you need to set a var with the remove value : the doc about this 使用动态ID进行销毁时,您需要设置一个带有remove值的var: 关于此的文档
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)
a better way if you don't need to keep the deleted object is to use the keyword delete
如果您不需要保留已删除的对象,则更好的方法是使用关键字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)
I don't think it's possible to cleanly achieve with ES6 destructuring. 我认为ES6的解构不可能完全实现。 Since other answers include mutating the state, try this instead: 由于其他答案包括更改状态,因此请尝试以下方法:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.