Skip to main content

How to Remove "null" or "undefined" Values from an Object in JavaScript

A common data cleaning task is to remove all keys from an object that have null or undefined values. This is often necessary before sending a payload to an API, saving data to a database, or simply to standardize an object's structure.

This guide will demonstrate the modern, non-mutating approach using Object.fromEntries() which is the recommended best practice. We will also cover the traditional, mutating approach using a for...in loop and the delete operator.

The Core Task: Mutating vs. Non-Mutating

Before choosing a method, you must decide if you want to modify the original object or create a new, cleaned one.

  • Non-mutating (Immutable): Creates a new object with the desired changes. The original object is left untouched. This is the recommended best practice in modern JavaScript as it is safer and leads to more predictable code.
  • Mutating: Modifies the original object in place. This can be useful for performance in specific cases but can cause unintended side effects if other parts of your code rely on the original object.

This modern, declarative approach is the cleanest and safest way to remove unwanted properties.

Problem: you have an object with null and undefined values that you want to remove.

// Problem: Create a new object without the 'age' and 'lastLogin' properties.
let user = {
id: 1,
name: 'Alice',
age: null,
lastLogin: undefined,
};

Solution:

  1. Convert the object into an array of [key, value] pairs using Object.entries().
  2. Filter this array to keep only the pairs where the value is not null or undefined.
  3. Convert the filtered array back into an object using Object.fromEntries().
function removeNullUndefined(obj) {
let entries = Object.entries(obj);

let filteredEntries = entries.filter(([key, value]) => value != null);

return Object.fromEntries(filteredEntries);
}

// Example Usage:
let user = { id: 1, name: 'Alice', age: null, lastLogin: undefined };
let cleanUser = removeNullUndefined(user);

console.log(cleanUser); // Output: { id: 1, name: 'Alice' }
console.log(user); // Output: { id: 1, name: 'Alice', age: null, lastLogin: undefined } (Original is unchanged)
note

This can also be written as a concise one-liner:

let cleanUser = Object.fromEntries(
Object.entries(user).filter(([key, value]) => value != null)
);

The Mutating Method: for...in and delete

If you need to modify the original object in place, the traditional for...in loop with the delete operator is the way to go.

Solution:

let user = {
id: 1,
name: 'Alice',
age: null,
lastLogin: undefined,
};

for (let key in user) {
if (user[key] == null) {
delete user[key];
}
}

console.log(user); // Output: { id: 1, name: 'Alice' }
// The original `user` object has now been modified.
note

This method is more direct and can be more performant for very large objects as it avoids creating new arrays and objects.

A Note on null == undefined

Both solutions use the loose equality operator (== or !=) to check for null. This is a deliberate and useful feature of JavaScript. The condition value == null is true for both null and undefined, but false for all other "falsy" values like 0, false, and '' (empty string).

console.log(null == undefined);    // Output: true
console.log(0 == null); // Output: false
console.log('' == null); // Output: false

This makes value != null the perfect, concise filter for removing only null and undefined values while keeping other falsy values.

Handling Nested Objects

To remove null or undefined values from nested objects, you must use a recursive function. This is an extension of the non-mutating approach.

Solution:

function removeNullUndefinedRecursively(obj) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, value]) => value != null)
.map(([key, value]) => [
key,
// If the value is an object (but not null), recurse.
typeof value === 'object' ? removeNullUndefinedRecursively(value) : value,
])
);
}

// Example Usage:
let nestedObj = {
id: 1,
data: {
value: 100,
notes: null, // Should be removed
},
config: undefined, // Should be removed
};

let cleanNestedObj = removeNullUndefinedRecursively(nestedObj);
console.log(cleanNestedObj); // Output: { id: 1, data: { value: 100 } }

Conclusion

Cleaning null and undefined values from objects is a simple task with modern JavaScript, but it's important to choose the right approach.

  • The non-mutating Object.fromEntries() method is the recommended best practice. It is declarative, safe (as it doesn't cause side effects), and easy to read.
  • The mutating for...in loop with delete is a valid alternative if you have a specific need to modify the original object in place.
  • Use the value != null condition as a concise and reliable way to check for both null and undefined.