How to remove object properties in JavaScript

How to remove object properties in JavaScript:

This post will show you how to remove properties from a JavaScript object. Objects hold key-value pairs. Each key-value pair is called the property of an object.

For example:

let student = {
    name: 'Alex',
    age: 20
}

This is an object holding two properties. One is the name of a student and another is the age. We can use the keys of an object to access and modify the values for that specific key.

Let me show you how we can delete any of the properties of an object.

Method 1: By using the delete operator:

The delete operator can be used to remove a property from an object in JavaScript. It has the following syntax:

delete expression

It can be used as like below:

delete obj.property
delete obj['property']

Where obj is the object and property is the property to delete.

Unless the property is an own non-configurable property, it will return true. Else, it returns false. For own non-configurable properties in strict mode, it throws TypeError.

Note that if the property we are trying to delete doesn’t exist, it will return true.

Let’s take a look at the below example:

let student = {
  name: "Alex",
  age: 20,
};

delete student.name;

console.log(student);

student object has two properties and we removed one with key name. It will print:

{ age: 20 }

JavaScript remove object property

Or, we can write the same program as:

let student = {
  name: "Alex",
  age: 20,
};

delete student["name"];

console.log(student);

It will print the same output.

You can use it in a similar way with nested objects as well:

let student = {
  name: "Alex",
  age: 20,
  address: {
    house: 'A/B',
    state: 'S'
  }
};

delete student.address.house;

console.log(student);

It will print:

{ name: 'Alex', age: 20, address: { state: 'S' } }

Method 2: Object destructing:

The above example of delete operator is a mutable approach i.e. it modifies the original object. If you want to create a new object without changing the original object, we can use object destructing.

For example:

let student = {
  name: "Alex",
  age: 20,
};

const { name, ...studentCopy } = student;

console.log(student);
console.log(studentCopy);

It will create a new object studentCopy and removes the property name: “Alex”.

The only problem is that it will create unnecessary objects. It is better to use delete if it is not an issue on changing the original object.

The advantage of this approach is that you can remove multiple properties at once without executing the same step again and again.

let student = {
  name: "Alex",
  age: 20,
  address: "A/B",
};

const { name, address, ...studentCopy } = student;

console.log(studentCopy);

This example removes both name and address properties of student and studentCopy will hold only age.

It will print:

{ age: 20 }

You might also like: