Search code examples
javascriptobjectlodash

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


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 attributes should stay.


Solution

  • If you want to remove all falsey values then the most compact way is:

    For Lodash 4.x and later:

    _.pickBy({ a: null, b: 1, c: undefined }, _.identity);
    >> Object {b: 1}
    

    For legacy Lodash 3.x:

    _.pick(obj, _.identity);
    
    _.pick({ a: null, b: 1, c: undefined }, _.identity);
    >> Object {b: 1}