Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all properties from a object

I have this Javascript object.

req.session 

In my code I add properties to this object. These properties can be other objects, arrays, or just plain strings.

req.session.savedDoc = someObject;  req.session.errors = ['someThing', 'anotherThing', 'thirdThing']; req.session.message = 'someString' 

If I later would like to erase all added properties of this object, what is the easiest/best way?

There must be a better way than this?

// Delete all session values delete req.session.savedDoc; delete req.session.errors; delete req.session.message; 
like image 874
Anders Östman Avatar asked Oct 11 '13 11:10

Anders Östman


People also ask

How do I remove all properties of an object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do I remove a property name from an object?

The delete operator is used to remove these keys, more commonly known as object properties, one at a time. The delete operator does not directly free memory, and it differs from simply assigning the value of null or undefined to a property, in that the property itself is removed from the object.

How do you remove a property of an object in Python?

You can delete the object property by using the 'del' keyword.


1 Answers

@VisioN's answer works if you want to clear that specific reference, but if you actually want to clear an object I found that this works:

for (var variableKey in vartoClear){     if (vartoClear.hasOwnProperty(variableKey)){         delete vartoClear[variableKey];     } } 
like image 73
Dave Lugg Avatar answered Oct 13 '22 18:10

Dave Lugg