Delete multiple object properties?

I'm sure you are trying to add custom properties to an object.

A simpler way I would suggest is by creating a sub property:

objOpts.custom.option4 = 'Option4'
objOpts.custom.option5 = 'Option5'

this way you could delete objOpts.custom and get done with it. Note that after this step you would have to recreate objOpts.custom = {}.

Moreover this way would also feel closer to OOP, since your public properties would easily be distinguishable from private ones.

If you are beginning with deleting objects in JavaScript, I'd like to point to to an excellently written article on the topic: http://perfectionkills.com/understanding-delete/

You could play around with the meta properties which allow you to protect properties from being deleted etc. (to create an even better coding flow for your case)

EDIT:

I'd like to add that instead of deleting and recreating the property, you could simply say objOpts.custom = {} which would release the option4 and option5 from memory (eventually, via Garbage Collection).


ES6 provides an elegant solution to this: Rest in Object Destructuring:

let { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 };
console.log(rest); // { c: 30, d: 40 }

Note that this doesn't mutate the original object, but some folks might still find this useful.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment


There is one simple fix using the library lodash.

The _.omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array.

This is a neat way of removing keys as using this you get a new object and the original object remains untouched. This avoids the problem of mutation where if we removed the keys in the original object all the other parts of code using that object might have a tendency to break or introduce bugs in the code.

Example

var obj = {x:1, y:2, z:3};
var result = _.omit(obj, ['x','y']);
console.log(result);

//Output
result = {z:3};

Link for the documentation of the same Click Here