DEV Community

Cover image for Destructure an object to remove a property
Tim Deschryver
Tim Deschryver

Posted on • Edited on • Originally published at timdeschryver.dev

23 3

Destructure an object to remove a property

Follow me on Twitter at @tim_deschryver | Originally published on timdeschryver.dev.


Destructure an object to remove a property

Use case

I want to delete a property from an object in a pure (immutable) way.

Solution

Use a destructuring assignment to assign the to be removed property to a variable, while cloning the "rest" properties to a new variable.
The _ is used to prevent a linter giving the variable is declared but its value is never read warning.

const { password: _, ...user } = {
  id: 47,
  username: 'tim',
  password: 'iliketrains',
}

console.log(user)
// |> { id: 47, username: 'tim' }
Enter fullscreen mode Exit fullscreen mode

For more examples see Destructuring assignment on MDN


Follow me on Twitter at @tim_deschryver | Originally published on timdeschryver.dev.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay