【问题标题】:ES6 destructuring: How do I create a new object that omits dynamically referenced keysES6 解构:如何创建一个忽略动态引用键的新对象
【发布时间】:2019-02-09 12:00:55
【问题描述】:

当键引用是动态的时,是否有使用解构和扩展运算符创建一个新对象的 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 执行此操作的方式(如果存在的话)。

在此先感谢

【问题讨论】:

  • 你为什么不直接使用地图?这里似乎比较合适。即使你想要实现的东西是可能的,它也是超级不可读的

标签: javascript ecmascript-6 javascript-objects


【解决方案1】:

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

【讨论】:

  • 你的第一个 sn-p 回答了我的问题。
  • @user2190690 我给了第二个 sn-ps,因为关键字 delete 接近你想要的
【解决方案2】:

我认为使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 2019-02-04
    • 2019-03-13
    • 2016-10-16
    • 2020-01-16
    • 1970-01-01
    • 2023-02-07
    • 2020-10-11
    相关资源
    最近更新 更多