Destructure an object to remove a property
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 warning "variable is declared but its value is never read".
const { password: _, ...user } = {id: 47,username: 'tim',password: 'iliketrains',};console.log(user);// |> { id: 47, username: 'tim' }
For more examples see Destructuring assignment on MDN
Feel free to update this blog post on GitHub, thanks in advance!
Enjoying the blog?
Support my work
If you enjoyed this post and found it useful, consider supporting my work. It helps me keep creating and sharing content like this. Thank you!