How to Delete an Object Key in JavaScript

How can we delete a key from an object in JavaScript?

Suppose we have an object obj.

const obj = {
  id: 0,
  name: "Bob"

We want to delete the name key such that obj only has an id.

Mutate object using delete

If we want to mutate the original object, we can easily use the delete key.

const key = "name";
delete obj[key];
// OR
delete obj["name"];
// OR

Return new object with destructuring

If we don’t want to modify the original object and simply return a new object without the field, we can use object destructuring.

const { name, } = obj;

The object rest will contain a shallow copy of all the fields in obj except for name.

Feel free to read more on array and object destructuring in JavaScript.