JavaScript: Removing a property from an object immutably by destructuring it

Say you have a JavaScript object like this:

const user = {
    firstName: 'Bramus',
    lastName: 'Van Damme',
    twitter: 'bramus',
    city: 'Vinkt',
    email: 'bramus@bram.us',
};

And now say you want to create a copy of the whole object, except for the email property.

The first idea that came to my mind was to clone/copy it and then successively remove email from the new object using the delete operator:

const userWithoutEmail = Object.assign({}, user);
delete userWithoutEmail.email;

Thanks to Destructuring and Object Rest/Spread Properties (currently stage 3) however, we can also do this:

const {
    email,
    ...userWithoutEmail
} = user;

This little piece of code destructures email off the user object, and the collects all rest props into userWithoutEmail. Handy!

This is part of a talk on ESNext named “What’s next
 for JavaScript?” which I recently gave at a Fronteers België meetup. I’m currently still in the process of preparing the slides for publication.

Original Content ,

One Response to JavaScript: Removing a property from an object immutably by destructuring it

  1. Pingback: JavaScript: What’s new in ECMAScript2018? | Bram.us

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.