ES6 解构:如何创建一个省略动态引用键的新对象

use*_*690 2 javascript javascript-objects ecmascript-6

当键引用是动态的时,是否有 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
Run Code Online (Sandbox Code Playgroud)

除非这是我目前的 Babel 设置,否则我无法弄清楚 ES6 的清洁方式(如果存在的话)。

提前谢谢了

jon*_*ano 7

使用动态 id 进行解构时,您需要设置一个带有移除值的 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)
Run Code Online (Sandbox Code Playgroud)

如果您不需要保留已删除的对象,更好的方法是使用关键字 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)
Run Code Online (Sandbox Code Playgroud)