Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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).

Many thanks in advance

like image 499
user2190690 Avatar asked Oct 24 '25 16:10

user2190690


2 Answers

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)
like image 107
jonatjano Avatar answered Oct 26 '25 07:10

jonatjano


I don't think it's possible to cleanly achieve with ES6 destructuring. 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);
like image 23
Tomasz Bubała Avatar answered Oct 26 '25 06:10

Tomasz Bubała



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!