Remove properties from objects (JavaScript)

Asked : Nov 17

Viewed : 19 times

Say I create an object as follows:

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

How should I remove the property regex to end up with new myObject as follows?

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
};
json javascript regex object properties 

Nov 17

3 Answers

To remove a property from an object (mutating the object), you can do it 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);

If you'd like a new object with all the keys of the original except some, you could use destructuring.

Demo

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

const {regex, ...newObj} = myObject;

console.log(newObj);   // has no 'regex' key
console.log(myObject); // remains unchanged

answered Dec 31


The delete operator deletes a property from an object:

Example

var person = {
  firstName:"John",
  lastName:"Doe",
  age:50,
  eyeColor:"blue"
};

delete person.age;  // or delete person["age"];

// Before deletion: person.age = 50, after deletion, person.age = undefined

answered Dec 31


Remove Property from a Javascript Object (2 Ways)

Method 1 - Using delete Operator

The delete operator removes the given property from the object. This operation is mutable, and the value of the original object is changed.

To delete multiple properties from the object, delete needs to be used multiple times.

let ob = {
	id: 100,
	name: "John",
	age: 28,
};

// delete "name" property
delete ob.name;

// { id: 100, age: 28 }
console.log(ob);

Method 2 - Using Destructuring Operator

By destructuring the object and using the rest syntax, a new object can be created having all the properties of the original object except some. This is an immutable operation, and the original object is left unchanged.

let ob = {
	id: 100,
	name: "John",
	age: 28,
	gender: "M"
};

// assign properties (except "id" & "name") to mics
let { id, name, ...mics } = ob;

// { age: 28, gender: "M" }
console.log(mics);

The downside is that new variables for the unintended properties are also created unnecessarily.

answered Dec 31


Login and Submit Your Answer
Browse other questions tagged  json  javascript  regex  object  properties or ask your own question.