How to Remove a Null from an Object in Lodash ?
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:
Table of Content
- Using omitBy and isNull Functions
- Using pickBy Function
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.
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.
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' }