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.

Example: Here, the removeBlankAttributes function is used to create a new object (objectWithoutBlankAttributes) by excluding properties with null or undefined values from the original object. The resulting object only contains non-blank attributes.

Javascript




function removeBlankAttributes(obj) {
    const result = {};
    for (const key in obj) {
        if (obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key];
        }
    }
    return result;
}
 
const originalObject = {
    name: 'John',
    age: null,
    city: 'New York',
    occupation: undefined,
};
 
const objectWithoutBlankAttributes = removeBlankAttributes(originalObject);
console.log(objectWithoutBlankAttributes);


Output

{ name: 'John', city: 'New York' }

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

...