How to remove undefined and null values from an object using lodash?

前端 未结 23 2335
既然无缘
既然无缘 2020-11-29 18:06

I have a Javascript object like:

var my_object = { a:undefined, b:2, c:4, d:undefined };

How to remove all the undefined properties? False

23条回答
  •  爱一瞬间的悲伤
    2020-11-29 18:25

    You can simply chain _.omit() with _.isUndefined and _.isNull compositions, and get the result with lazy evaluation.

    Demo

    var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value();
    

    Update March 14, 2016:

    As mentioned by dylants in the comment section, you should use the _.omitBy() function since it uses a predicate instead of a property. You should use this for lodash version 4.0.0 and above.

    DEMO

    var result = _(my_object).omitBy(_.isUndefined).omitBy(_.isNull).value();
    

    Update June 1, 2016:

    As commented by Max Truxa, lodash already provided an alternative _.isNil, which checks for both null and undefined:

    var result = _.omitBy(my_object, _.isNil);
    

提交回复
热议问题