Sunday, May 27, 2012

How to remove a property from a javascript object


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.


Source: Tips4all

2 comments:

  1. 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.

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

    delete myJSONObject.regex;

    alert ( myJSONObject.regex);


    works in FF and IE and I think all others

    ReplyDelete