JavaScript rest syntax can remove properties too
JavaScript rest syntax can remove properties too.
For example, given this object:
const user = {
name: "Cory",
address: {
city: "KC"
}
}
This creates a new user without the address object:
const { address, ...userWithoutAddress } = user;
#javascript
Update: Some asked, so here's how it works.
This snippet uses 2 features:
1 Object destructuring
2 Rest syntax
Object destructuring creates a variable that references a property.
So, this:
const { name } = user
Is shorthand for:
const name = http://user.name
So object destructuring is "syntactic sugar". It doesn't enable anything new. But it saves some keystrokes.
When you combine the rest syntax with object destructuring, you're saying: "Place all the properties I didn't destructure in this new object..."
In summary:
const { address, ...userWithoutAddress } = user
You can read this as:
"Use object destructuring to create a const called address that contains user.address. Also create an object called userWithoutAddress that contains all the user's properties, except address." 😎