➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
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!