3

Suppose I have some key-value object. I want to destructure dynamically from some key such that I can remove it and just get the remaining items in a new object.

const omit = (obj, key) => {
  const { [key], ...rest } = obj // Syntax error
  return rest
}

omit({ b: 1, c: 2, d: 3 }, 'd')
// desired output { b: 1, c: 2 }

Is there a way to do that?

Disclaimer: I know there are lots of workarounds but would like to do it with destructuring.

david_adler
  • 9,690
  • 6
  • 57
  • 97
  • @TheBombSquad the OP did. If `key` was passed in as 'c' the result should be `{b: 1, d: 3}`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – bburhans Jul 29 '21 at 21:38
  • Does this answer your question? [How to destructure into dynamically named variables in ES6?](https://stackoverflow.com/questions/35939289/how-to-destructure-into-dynamically-named-variables-in-es6) – Dominik Jul 29 '21 at 21:47
  • word ty @bburhans – The Bomb Squad Jul 29 '21 at 22:21

2 Answers2

4

In order to destructure on a dynamic key you will need to provide an alias for JS to bind that value to.

Firefox even gives you a helpful error message here: enter image description here

const omit = (obj, key) => {
  const { [key]: _, ...rest } = obj
  // CHANGE -----^
  return rest
}

console.log(omit({ b: 1, c: 2, d: 3 }, 'd'))
Dominik
  • 6,078
  • 8
  • 37
  • 61
3

You can rename the variables when destructuring, and the left side (preexisting name) can be in brackets like you want.

let {[key]: omitted, ...rest} = a;
bburhans
  • 539
  • 3
  • 12
  • MDN documentation on the renaming bit, not the dynamic names bit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assigning_to_new_variable_names – bburhans Jul 29 '21 at 21:53