5

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?

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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:

Comments

1

Using Lo-Dash, consider this implementation (using _.pick):

var newObject = _.pick(object, function onlyTruthy(val, key) {
  return !!val;
});

Comments

0

I think your code reads much more intuitively. Maybe he just didn't want to change the original object?

2 Comments

Not true, see Daniel's and Yacoby's answers.
Those answers and mine are not mutually exclusive. Well, at least they may not be. We don't have enough context to make a determination.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.