Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure from dynamic key

Tags:

javascript

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.

like image 701
david_adler Avatar asked Sep 16 '25 21:09

david_adler


1 Answers

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'))
like image 187
Dominik Avatar answered Sep 19 '25 05:09

Dominik