How to remove a property from an object in JavaScript?
This article is about how to remove a property from an object in javascript using delete operator.
In this short article, we will learn how to delete a property from a JavaScript object.
JavaScript objects are collections of different properties and types, each property has a name and a value.
Using delete operator
To delete a property from a given JavaScript object we can use the delete operator. In JavaScript, the delete operator is use to remove a property from an object.
Syntax:
delete object.property //or delete object['property']
Suppose we have an object person, with name, address, and occupation as properties.
const person = { name : 'John', address: 'New York', occupation: 'Engineer' }
So to remove the property occupation from the person object we can use delete like this.
const person = { name : 'John', address: 'New York', occupation: 'Engineer' } delete person.occupation console.log(person)
Output:
{ name: 'John', address: 'New York' }
As you can see, the object no longer have the occupation property.
You can also use the square bracket instead of using dot property accessor.
delete person['occupation']
However, if you don't want to delete the property and just remove the value of it, you can just set the property value to undefined .
Setting JavaScript Object Property to undefined
Setting the property to undefined is considered to be much faster than deleting the whole property if you are operating on a large number of objects.
To set the property to undefined, you can use a dot or square bracket property accessor.
Example:
const person = { name : 'John', address: 'New York', occupation: 'Engineer' } person.occupation = undefined //OR person['occupation'] = undefined console.log(person)
Output:
{ name: 'John', address: 'New York', occupation: undefined }
Related Posts
Use Array forEach() to loop through JavaScript object
FInd out how to use forEach in an object and return key, value and also convert it's properties to an array using JavaScript.
JavaScript hasOwnProperty() method of an Object
Tutorial about the Javascript hasOwnProperty() method of an object, its use, advantages and limitations.
How to add getter to an existing JavaScript Object
Short tutorial on adding a getter to an existing JavaScript object using Object.defineProperty method.
How to add dynamic Key to an object in JavaScript
Short tutorial on how to create and add dynamic key to an object in JavaScript using bracket syntax and ES6 methods.
