The term you have used in your question title remove a property from a javascript object
, can be interpreted in some different ways, the one is to remove it for whole the memory an the list of object keys or the other is just to remove it from your object. as it has been mentioned in some other answers the delete
keyword is the main part. lets say you have your object like:
myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
if you do:
console.log(Object.keys(myJSONObject));
the result would be:
["ircEvent", "method", "regex"]
you can delete that specific key from your object keys like:
delete myJSONObject["regex"];
then your objects key using Object.keys(myJSONObject)
would be:
["ircEvent", "method"]
but the point is if you care about memory and you want to whole the object gets removed from the memory, it is recommended to set it to null before you delete the key:
myJSONObject["regex"] = null;
delete myJSONObject["regex"];
the other important point here is to be careful about your other references to the same object, for instance if you create a variable like:
var regex = myJSONObject["regex"];
or add it as a new pointer to another object like:
var myOtherObject = {};
myOtherObject["regex"] = myJSONObject["regex"];
Then even if you remove it from your object myJSONObject
, that specific object won't get deleted from the memory, since the regex
variable and myOtherObject["regex"]
still has their values. Then how could we remove the object from the memory for sure.
The answer would be to delete all the references you have in your code, pointed to that very object. and also not use var
statements to create new references to that object. This last point regarding var
statements, is one of the most crucial issues that we usually face with, because using var
statements would prevent the created object, from getting removed.
Which means in this case you won't be able to remove that object because you have created regex variable via var
statement, and if you do:
delete regex;//false
the result would be false
, which means that your delete statement hasn't been executed as you expected. But if you had not created that variable before and you only had myOtherObject["regex"]
as your last existing reference, you could have done this just by removing it like:
myOtherObject["regex"] = null;
delete myOtherObject["regex"];
In other word a JavaScript object gets killed as soon as there is no reference left in your code pointed to that object.