ES6解构:如何创建一个新对象,该对象忽略了动态引用的键 [英] ES6 destructuring: How do I create a new object that omits dynamically referenced keys

查看:286
本文介绍了ES6解构:如何创建一个新对象,该对象忽略了动态引用的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当键引用是动态的时,是否有一个ES6(及更高版本)解决方案使用解构和散布运算符来创建一个新对象,并从原始对象中删除了一个键和值,所以:

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:

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方法(如果存在).

Unless it's my present Babel setup, I can't figure out the clean ES6 way of doing this (if it exists).

非常感谢

推荐答案

使用动态ID进行结构分解时,您需要设置一个带有remove值的var:

when destructuring using dynamic id you need to set a var with the remove value : 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)

如果不需要保留删除的对象,更好的方法是使用关键字

a better way if you don't need to keep the deleted object is to use the keyword 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解构:如何创建一个新对象,该对象忽略了动态引用的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆