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); |
{ 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()