Removing property from a JSON object in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say, we create an object as follows −

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

We are required to illustrate the best way to remove the property regex to end up with new myObject as follows −

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

The delete operator is used to remove properties from objects −

const myObject = {
   "ircEvent": "PRIVMSG",
   "method": "newURI",
   "regex": "^http://.*"
};
delete myObject['regex'];
console.log(myObject.hasOwnProperty("regex")); // false

The delete operator in JavaScript has a different function to that of the keyword in C and C++ −

It does not directly free memory. Instead, its sole purpose is to remove properties from objects.

Output

Following is the console output −

False
raja
Published on 22-Oct-2020 13:17:25
Advertisements