How to remove a property from JavaScript object ?
Last Updated :
26 Jul, 2023
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:
- Using JavaScript delete keyword
- Using destructuring assignment
The JavaScript delete keyword is used to delete properties of an object in JavaScript.
Syntax:
delete object.property or
delete object[property]
Note:
- Delete keyword deletes both the property’s and the property’s value. After deletion, the property can not be used.
- The delete operator is designed to use on object properties. It can not be used on variables or functions.
- Delete operators should not be used on predefined JavaScript object properties. It can cause problems.
Example 1: This example deletes the address property of an object.
Javascript
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.
Javascript
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.
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:
Javascript
const p = {
name: "person1" ,
age: 50,
address: "address1"
};
const { age, ...updatedObject } = p;
console.log(updatedObject);
|
Output
{ name: 'person1', address: 'address1' }
Share your thoughts in the comments
Please Login to comment...