How to Remove a null from an Object in JavaScript

Using Vanilla JavaScript

You can use vanilla JavaScript to remove nulls from objects using Object.fromEntries(), Object.entries() and Array filter().

Using these three methods we can remove null values from an Object

Here we are using above there methods to remove null values from and object. We can also use the same logic to remove undefined and empty string values from and object.

const obj = {id: 123, name: 'Tony', city: null, state: undefined, phoneNo: null};

const result = Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== null));

console.log(result);

Output:

{ id: 123, name: 'Tony', state: undefined }

The Object.fromEntries() method creates an object from a list of key/value pairs.

const arr = [
    ['id', 123],
    ['name', 'Tony'],
    ['city', null],
    ['state', undefined],
    ['phoneNo', null]
];
    
const result = Object.fromEntries(arr);

console.log(result);

Output:

{ id: 123, name: 'Tony', city: null, state: undefined, phoneNo: null }

The Object.entries() method returns an array of the key/value pairs of an object.
The Object.entries() method does not change the original object.

const obj = { id: 123, name: 'Tony', city: null, state: undefined, country: null };

const result = Object.entries(obj);

console.log(result);

Output:

[
    ['id', 123],
    ['name', 'Tony'],
    ['city', null],
    ['state', undefined],
    ['country', null]
]

The filter() method creates a new array filled with elements that pass a test provided by a function.
The filter() method does not execute the function for empty elements.
The filter() method does not change the original array.

const arr = [
    ['id', 123],
    ['name', 'Tony'],
    ['city', null],
    ['state', undefined],
    ['phoneNo', null]
];

const result = arr.filter(([key, value]) => value !== null);

console.log(result);

Output:

[ [ 'id', 123 ], [ 'name', 'Tony' ], [ 'state', undefined ] ]

Leave a Comment

Your email address will not be published. Required fields are marked *