tags:

views:

19596

answers:

2

Say I create an object thus:

var myJSONObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to remove the property 'regex'? i.e. I would like to end up with myJSONObject such that:

myJSONObject ==
        {"ircEvent": "PRIVMSG", "method": "newURI"};

Thanks.

+89  A: 

like this:

delete myJSONObject.regex;
// or,
delete myJSONObject['regex'];
// or,
var prop = "regex";
delete myJSONObject[prop];

Update: For anyone interested in reading more about it, kangax has written an incredibly in-depth blog post about the delete statement on his blog. Understanding delete. Highly recommended.

nickf
Is it possible to use associative array syntax with delete? Say i have the name of the property as a string i.e. 'regex'.
johnstok
Checked, it also works with "delete myJSONObject['regex'];"See: http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
johnstok
Irritatingly MS fail to mention that in their own JScript documentation on MSDN.
AnthonyWJones
An upshot of one of the observations at the "understanding delete" link above, is that, since you cannot necessarily delete a variable, but only object properties, you therefore cannot delete an object property "by reference" -- var value=obj['prop']; delete value //doesn't work
George Jempty
+5  A: 
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

delete myJSONObject.regex;

alert ( myJSONObject.regex);

works in FF and IE and I think all others

redsquare