Remove Property from a Javascript Object (2 Ways)

javascript
Published on March 22, 2021

This tutorial discusses two ways of removing a property from an object. The first way is using the delete operator, and the second way is object destructuring which is useful to remove multiple object properties through a single line of code.

Method 1 - Using delete Operator

The delete operator removes the given property from the object. This operation is mutable, and the value of the original object is changed.

To delete multiple properties from the object, delete needs to be used multiple times.

let ob = {
	id: 100,
	name: "John",
	age: 28,
};

// delete "name" property
delete ob.name;

// { id: 100, age: 28 }
console.log(ob);

Method 2 - Using Destructuring Operator

By destructuring the object and using the rest syntax, a new object can be created having all the properties of the original object except some. This is an immutable operation, and the original object is left unchanged.

let ob = {
	id: 100,
	name: "John",
	age: 28,
	gender: "M"
};

// assign properties (except "id" & "name") to mics
let { id, name, ...mics } = ob;

// { age: 28, gender: "M" }
console.log(mics);

The downside is that new variables for the unintended properties are also created unnecessarily.

In this Tutorial
    Comments
    Loading Comments