Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing falsies from JavaScript object

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?

like image 736
NumbNuts2022 Avatar asked Jul 21 '10 21:07

NumbNuts2022


People also ask

Can we remove a key from object in JavaScript?

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.

How do I remove a property from an object without mutating?

A better way to delete a property without mutating is by using spread operator. const {worth, … newPerson} = person; console.

How do I remove a property from an object?

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, ...

How do I remove something from JavaScript?

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.


2 Answers

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

like image 70
Yacoby Avatar answered Oct 11 '22 01:10

Yacoby


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:

  • Mozilla Dev Center: delete Operator
like image 33
Daniel Vassallo Avatar answered Oct 11 '22 03:10

Daniel Vassallo