How to Remove a null from an Object with Lodash

Jun 8, 2022

To remove a null from an object with lodash, you can use the omitBy() function.

const _ = require('lodash');

const obj = {a: null, b: 'Hello', c: 3, d: undefined};

const result = _.omitBy(obj, v => v === null); // {b: 'Hello', c: 3, d: undefined}

If you want to remove both null and undefined, you can use .isNull or non-strict equality.

const _ = require('lodash');

const obj = {a: null, b: 'Hello', c: 3, d: undefined};

const result = _.omitBy(obj, _.isNull); // {b: 'Hello', c: 3}

const other = _.omitBy(obj, v => v == null); // {b: 'Hello', c: 3}

Using Vanilla JavaScript

You can use vanilla JavaScript to remove nulls from objects using Object.entries() and Array filter(). However, the syntax is a bit messy. Lodash omitBy() is cleaner.

const obj = {a: null, b: 'Hello', c: 3, d: undefined, e: null};

Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== null)); // { b: "Hello", c: 3, d: undefined }

More Lodash Tutorials