post-ad

Remove Property From Object In JS

In this article, we will discuss the 2 ways to remove object properties in JavaScript. So let’s start it.

Ways To Remove Object Property

  1. Using Delete Operator
  2. Using Destructuring Operator

1. Using Delete Operator

This Operator will remove the given property from the object. Using this we can remove single property at a time. To remove multiple properties, we need to write delete multiple times. Try the below code.

var obj = {
  StudId: 10,
  StudName: "John",
  StudClass: "A",
};

// delete "StudName" property
delete obj.StudName;

// { StudId: 10, StudClass: "A" }
console.log(obj);

2. Using Destructuring Operator

Using the destructuring method, we can create a new object with all the old properties of the old object except some. Using this method we can remove unwanted properties at a time in a single statement. Try the below code.

var obj = {
  StudId: 10,
  StudName: "John",
  StudClass: "A",
    StudDept: "Commerce"
};

// assign properties to newObj except "StudId" & "StudName"
let { StudId, StudName, ...newObj } = obj;

// { StudClass: "A", StudDept: "Commerce" }
console.log(newObj);

Submit a Comment

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

Subscribe

Select Categories

page-ad