14 July, 2018 Tags: , ,

Quick Javascript tip: Deleting object properties with the delete operator

You have a given object, and for some reason you don’t want this object to be available with property x or y, in my case I needed to return a object with the user information, but for obvious reason I didn’t want this same object to have sensitive information like password and other personal data.

Meet the delete operator

delete Object.property;

As simple as this: you have an object and you want to remove a property, then the delete operator is the quicker way to go, instead of creating a whole new object.

The delete operator removes a property from an object, and returns true if the operation succeeded, or false when the delete operation is not concluded.

Example: Customer information

const Customer = {
  firstName: 'Firmino',
  lastName: 'Changani',
  country: 'Angola',
  username: 'firmino.changani',
  email: '[email protected]',
  password: '$2a$04$DuEiqY4qbDAwzujtIbzPS.2dOmex0UGXUkNBdzKoViSy28ibet2fy'
}

In any point of an ecommerce web application we could have the information of a customer stored in a variable / constant, and we need to return this information as response of a GET request, let’s say that the user is want to see his profile information. To remove the information about the password we just need to follow the syntax presented above:

delete Customer.password;

The console should return:

true

Just like I said in the beginning, this is a quick tip post, and of course that there’s more thing that you can read / learn about the delete operator. I would love to read your thoughts in the comments. Thank you.

Read more on:

OTHER ARTICLES