Search code examples
javascriptlodash

Remove just undefined (not null)


I am using library Lodash and I need from my javascript object remove just possible undefined properties, but I want keep null properties.

for example if I would have object like this:

var fooObject = {propA:undefined, propB:null, propC:'fooo'};

I expect output like this:

{propB:null, propC:'fooo'}

I tried this:

.pickBy(fooObject, _.identity);

but it remove also null values. Does Lodash contain some function for that? Thanks.


Solution

  • Try using .omitBy method .

    For undefined and null values.

    _.isUndefined and _.isNull

     var fooObject = {propA:undefined, propB:null, propC:'fooo'};
    

    To remove undefined values from object

    var newObj= _(fooObject).omitBy(_.isUndefined).value();
     console.log(newObj);
    

    Incase,If you want to remove both undefined and null

    var result = _(fooObject).omitBy(_.isUndefined).omitBy(_.isNull).value();
    console.log(result);
    

    Hope this helps..!