So I write a short function to remove members from an object that have falsy values:
for (var key in object) {
if (!object[key]) {
delete object[key];
}
}
A couple days later I check source control and someone has changed this to:
var newObject = {};
for (var key in object) {
if (object[key]) { newObject[key] = object[key]; }
}
return newObject;
There's no comments on the check-in and the guy is not here today at work.
Which implementation is better? What are the performance implications of each method?
Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.
A better way to delete a property without mutating is by using spread operator. const {worth, … newPerson} = person; console.
In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...
The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.
You cannot delete a property on an object that it inherits from a prototype. So in some cases your code may fail to work as expected.
Source
You cannot delete
a property of an object that it inherits from a prototype
(although you can delete it directly on the prototype).
In the second example, a falsy property inherited from a prototype
will not be copied to the newObject
.
Further reading:
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