Open In App

How to Remove a Null from an Object in Lodash ?

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Removing Null values from Objects is important for data cleanliness and efficient processing in Lodash.

Below are the approaches to Remove a null from an Object in Lodash:

Run the below command:

npm i lodash

Using omitBy and isNull Functions

In this approach, we are using Lodash’s omitBy function with _.isNull as the predicate to create a new object without properties that have null values, removing nulls from the original object and resulting in the cleaned result.

Example: The below example uses omitBy and isNull functions to Remove a null from an Object in Lodash.

JavaScript
const _ = require('lodash');
let data = {
    name: 'GFG',
    age: null,
    city: 'Noida',
    country: null
};
let res = _.omitBy(data, _.isNull);
console.log(res);

Output:

{ name: 'GFG', city: 'Noida' }

Using pickBy Function

In this approach, we are using Lodash’s pickBy function with _.identity as the predicate to create a new object with properties that are not null, removing null values and producing the cleaned result.

Example: The below example uses the pickBy function to Remove a null from an Object in Lodash.

JavaScript
const _ = require('lodash');
let data = {
    name: 'GFG',
    age: null,
    city: 'Noida',
    country: null
};
let res = _.pickBy(data, _.identity);
console.log(res);

Output:

{ name: 'GFG', city: 'Noida' }

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads