Delete Property From Object In JavaScript

Delete Property From Object In JavaScript | In JavaScript, you can delete properties from an object using the delete operator. The delete operator allows you to remove a property from an object, effectively removing its value and making it undefined. In this article, we’ll cover the basic syntax of the delete operator and provide five examples of how to use it to delete properties from an object in JavaScript.

Basic Syntax:-
delete objectName.propertyName;

Delete Property From A Simple Object In JavaScript

let person = { name: "John", age: 30 };
delete person.age;
console.log(person);

Output:-

{ name: ‘John’ }

Removing A Property From A Nested Object

let person = {
  name: "John",
  address: { street: "123 Main St", city: "New York" },
};
delete person.address.city;
console.log(person);

Output:-

{ name: ‘John’, address: { street: ‘123 Main St’ } }

Using Delete To Remove Properties From An Object Created Using A Constructor Function

function Person(name, age) {
  this.name = name;
  this.age = age;
}

let john = new Person("John", 30);
delete john.age;
console.log(john);

Output:-

Person { name: ‘John’ }

Removing Properties From An Object Created Using An Object Literal

let person = { name: "John", age: 30 };
delete person["age"];
console.log(person);

Output:-

{ name: ‘John’ }

Removing Properties From An Object That Is Part Of An Array

let people = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
];
delete people[0].age;
console.log(people);

Output:-

[ { name: ‘John’ }, { name: ‘Jane’, age: 25 } ]

In conclusion, deleting properties from an object in JavaScript is straightforward using the delete operator. The delete operator allows you to remove properties from an object and make their values undefined. Remember that delete only works on objects, so it cannot be used to delete variables or elements from an array. Use the delete operator wisely and always check the object after removing properties to ensure it meets your needs.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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