In the previous blog we saw how to remove null from an Array using Lodash. If you haven’t checked that blog, please read it once to understand what Lodash is.
In this tutorial we will see how to remove null from an object with Lodash. At this stage, we believe that you know the difference between objects and arrays in JavaScript.
Table of Contents
With Lodash
Remove null from an object with Lodash
To remove a null from an object with Lodash, we will use the omitBy() function provided by the Lodash library. Let’s see an example for the same.
Code
const _ = require('lodash');
const obj = {a: null, b: 'CodingIsEasy', c: 4, d: undefined};
const result = _.omitBy(obj, v => v === null); // {b: 'CodingIsEasy', c: 4, d: undefined}
Remove null & undefined from an object with Lodash
If we want to remove null and undefined both, we can use .isNull or non-strict equality. Example is given below for the same.
Code
const _ = require('lodash');
const obj = {a: null, b: 'CodingIsEasy', c: 4, d: undefined};
const result = _.omitBy(obj, _.isNull); // {b: 'CodingIsEasy', c: 4}
const other = _.omitBy(obj, v => v == null); // {b: 'CodingIsEasy', c: 4}
Without Lodash
Remove null from an object in JS without Lodash
Even without using lodash, we can accomplish this goal by using only vanilla Javascript. Vanilla JS can be used to remove null from objects using Object.entries() and Array filter(). The syntax is a bit long and messy that’s another reason to use Lodash’s omitBy() to write clean code.
Code
const obj = {a: null, b: 'CodingIsEasy', c: 4, d: undefined, e: null};
Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== null));
// { b: "CodingIsEasy", c: 4, d: undefined }
Hope you have understood the code and the functions used in this tutorial. Comment below if you have any doubts.
1 thought on “How to remove null from an Object w/wo Lodash?”