Removing Null Values from an Object Using reduce()

The removeNullUndefinedWithReduce function uses the reduce() method and Object.entries() to iterate through the properties of the object. It creates a new object, excluding properties with null or undefined values. For nested objects, it recursively applies the same logic. This approach is functional and produces a new object without modifying the original one.

Example: Here, the removeNullUndefinedWithReduce function is used to create a new object (cleanedObject) by excluding properties with null or undefined values. The reduce() method is employed for a functional approach, and the resulting cleanedObject does not modify the original object. The cleaning process includes nested objects.

Javascript




function removeNullUndefinedWithReduce(obj) {
    return Object.entries(obj).reduce((acc, [key, value]) => {
        if (value !== null && value !== undefined) {
            acc[key] = typeof value === 'object' ? removeNullUndefinedWithReduce(value) : value;
        }
        return acc;
    }, {});
}
 
const objectWithNullUndefined = {
    a: 1,
    b: null,
    c: 3,
    d: undefined,
    e: {
        f: null,
        g: 'hello',
        h: undefined,
    },
};
 
const cleanedObject = removeNullUndefinedWithReduce(objectWithNullUndefined);
console.log(cleanedObject);


Output

{ a: 1, c: 3, e: { g: 'hello' } }


Remove blank attributes from a JavaScript Object

Remove blank attributes from a JavaScript object we have to check if the values are null or undefined and then delete the blank attributes with approaches mentioned below.

Table of Content

  • Removing Blank Attributes from a JavaScript Object
  • Removing Null Values from an Object
  • Removing Null and Undefined Values from a Nested Object
  • Removing Null Values from an Object Using reduce()

Similar Reads

Removing Blank Attributes from a JavaScript Object

In this approach, we will iterate through the properties of the original object and create a new object, excluding any properties with values that are null or undefined....

Removing Null Values from an Object

...

Removing Null and Undefined Values from a Nested Object

This approach defines a function removeNullUndefined that directly modifies the original object by deleting properties with null or undefined values. It uses a for...in loop to iterate through the object’s properties and checks and deletes those properties with null or undefined values....

Removing Null Values from an Object Using reduce()

...