JavaScript Tips: Remove Unwanted Object Properties With Destructuring
Need to remove a property from an object?
Imagine you have a user
object and need to remove the email
property for privacy reasons.
There are a few ways to achieve this.
One of the simplest is combining object destructuring and the rest operator.
Let's dive into how you can do this with an example:
const user = { name: 'John Doe', email: 'john@example.com', age: 30 };
You aim to get a new object from this user without the email
property.
How to
JavaScript's destructuring assignment syntax comes to the rescue, coupled with the rest operator.
const { email, ...userWithoutEmail } = user;
What's happening here?
We're pulling out the email
from the user
object and capturing the rest of the properties (name
and age
in this case) into a new object called userWithoutEmail
.
The Result
After running the above code, if you inspect userWithoutEmail
, you'll see it doesn't have the email
property:
console.log(userWithoutEmail); // Output: { name: 'John Doe', age: 30 }
This method is slick for a couple of reasons.
First, it's concise. With just one line of code, you've filtered out a property.
Second, it's direct. There's no looping through properties or manually copying them over. Everything else in the object is automatically spread into the new object, userWithoutEmail
, minus the email
.
You can use this technique to remove many properties if needed.
It's a handy tool to keep in your JavaScript toolbox.