How to Remove Empty Objects from an Array in JavaScript
When processing data, you often end up with arrays that contain empty objects ({}). These can be the result of a transformation, an API response, or a data cleaning process. To standardize your data, you need an efficient way to filter out these empty objects.
This guide will demonstrate the modern and recommended best practice for removing empty objects from an array using Array.prototype.filter() in combination with Object.keys().
The Core Method (Recommended): Array.prototype.filter()
The filter() method is the perfect tool for this job. It creates a new array containing only the elements that pass a specific test. It is a non-mutating, functional approach, which is the preferred standard in modern JavaScript.
Problem: you have an array containing a mix of empty and non-empty objects, and you want to create a new array with only the non-empty ones.
// Problem: Remove the empty `{}` objects from this array.
let data = [
{ id: 1, name: 'Alice' },
{},
{ id: 2, name: 'Bob' },
{},
];
Solution: the test for an empty object is to check if it has any keys. Object.keys(obj).length === 0 is true only for an empty object.
function removeEmptyObjects(arr) {
return arr.filter(obj => {
// Keep the object if it has at least one key.
return Object.keys(obj).length > 0;
});
}
// Example Usage:
let data = [
{ id: 1, name: 'Alice' },
{},
{ id: 2, name: 'Bob' },
{},
];
let nonEmptyData = removeEmptyObjects(data);
console.log(nonEmptyData); // Output: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
console.log(data); // Output: (The original array is unchanged)
Output:
[ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'} ]
[ {id: 1, name: 'Alice'}, {}, {id: 2, name: 'Bob'}, {} ]
This can be written even more concisely:
let nonEmptyData = data.filter(obj => Object.keys(obj).length > 0);
How the filter() Method Works
newArray = oldArray.filter(callbackFunction)
filter()is called on an existing array.- It iterates over every element in that array.
- For each element, it calls the
callbackFunctionyou provided. - If the callback function returns a "truthy" value, the element is included in the new array.
- If the callback function returns a "falsy" value, the element is excluded.
- After checking all elements, it returns the newly created array.
In our solution, Object.keys(obj).length > 0 is the test.
- For a non-empty object like
{ id: 1 },Object.keys()returns['id'],lengthis1, so1 > 0istrue. The object is kept. - For an empty object
{},Object.keys()returns[],lengthis0, so0 > 0isfalse. The object is removed.
A Note on What "Empty" Means
This method specifically removes objects that have no enumerable own properties. It will not remove:
nullorundefinedvalues.- Empty arrays (
[]). - Objects whose properties are all
nullorundefined(e.g.,{ name: null }).
If you need to also filter out null and undefined, you can add a check for them.
let mixedData = [{}, null, { id: 1 }, undefined];
let cleanData = mixedData.filter(item => {
// Keep the item if it's not null/undefined AND it's not an empty object.
return item != null && Object.keys(item).length > 0;
});
console.log(cleanData);
Output:
[{ id: 1 }]
Handling Arrays with Mixed Data Types
The Object.keys() check can have unintended consequences in an array with mixed types, because Object.keys() on a non-object value can be surprising.
Problem:
let mixedArray = [{}, { id: 1 }, 'hello', 0, [], null];
// This will throw a TypeError because you cannot call Object.keys(null).
let result = mixedArray.filter(item => Object.keys(item).length > 0);
Solution: to safely handle a mixed array, you must first check if the item is a plain object before you check its keys.
let mixedArray = [{}, { id: 1 }, 'hello', 0, [], null, undefined];
let result = mixedArray.filter(item => {
// Check if the item is a plain object (and not null or an array)
let isPlainObject =
item !== null &&
typeof item === 'object' &&
!Array.isArray(item);
// If it's not a plain object, we want to keep it.
if (!isPlainObject) {
return true;
}
// If it IS a plain object, only keep it if it's not empty.
return Object.keys(item).length > 0;
});
console.log(result); // Output: [ { id: 1 }, 'hello', 0, [], null, undefined ]
Output:
[ {id: 1}, 'hello', 0, [], null, undefined ]
This correctly removes only the empty {} while preserving all other data types.
Conclusion
Filtering empty objects from an array is a simple data cleaning task with a clear, modern solution.
- The
Array.prototype.filter()method is the recommended best practice. It is non-mutating, declarative, and highly readable. - The standard test for an empty object is to check the length of its keys:
Object.keys(obj).length > 0. - Be mindful when working with arrays of mixed types. You may need to add additional checks to ensure you are only applying the
Object.keys()logic to plain objects.