Open In App

How to remove a property from JavaScript object ?

In this article, we will remove a property from a Javascript Object.

Below are the following approaches to removing a property from a JavaScript object:



Method 1: Using JavaScript delete keyword

The JavaScript delete keyword is used to delete properties of an object in JavaScript

Syntax:



delete object.property or
delete object[property]

Note:

Example 1: This example deletes the address property of an object. 




let p = {
    name: "person1",
    age:50,
    address:"address1"
};
 
delete p.address;
 
console.log("The address of "
    + p.name +" is " + p.address);

Output
The address of person1 is undefined

Example 2: This example deletes the age property of an object.




let p = {
    name: "person1",
    age: 50,
    address: "address1"
};
 
delete p.age;
 
console.log(p.name + " is "
    + p.age + " years old.");

Output
person1 is undefined years old.

Method 2: Using destructuring assignment

Destructuring Assignment is a JavaScript expression that allows us to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables.

Example:




const p = {
    name: "person1",
    age: 50,
    address: "address1"
};
// Destructure the object
//and omit the 'age' property
const { age, ...updatedObject } = p;
 
console.log(updatedObject);

Output
{ name: 'person1', address: 'address1' }


Article Tags :