开发者

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开发者_JAVA百科 guy is not here today at work.

Which implementation is better? What are the performance implications of each method?


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:

  • Mozilla Dev Center: delete Operator


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜