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;
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!
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.
You can delete the object property by using the 'del' keyword.
@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]; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With