I create an object with multiple properties -
var objOpts = { option1: 'Option1', option2: 'Option2', option2: 'Option3' };
I then add some more properties later on -
objOpts.option4 = 'Option4' objOpts.option5 = 'Option5'
I'm then done with the two latter created properties ('Option4' & 'Option5') and I want to clear/delete both.
Currently I'd do it like so -
delete objOpts.option4 delete objOpts.option5
Is there another way to go about doing this? Imagine I'd added 5 more properties and needed to clear/delete them all that'd be five lines of almost identical 'delete' code
Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!
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.
To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.
You can delete properties on objects by using the delkeyword: Example Delete the age property from the p1 object: del p1.age Try it Yourself » Related Pages
The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties.
The issue with delete is that it’s a mutable operation, physically changing the object and potentially causing unwanted side-effects due to the way JavaScript handles objects references. By using object destructuring, combined with the rest operator ...rest, we have a one-liner clean approach. What is Object destructuring?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With