Thursday, February 8, 2018

How do I remove a property from a JavaScript object?

Answer


Answer





Say I create an object as follows:



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


What is the best way to remove the property regex to end up with new myObject as follows?




var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};

Answer



Like this:



delete myObject.regex;

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


Demo




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

console.log(myObject);






For anyone interested in reading more about it, user kangax has written an incredibly in-depth blog post about the delete statement on their blog, Understanding delete. It is highly recommended.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...