How to Remove Empty Object from JSON in JavaScript ?

In JSON, empty objects can cause data inconsistency and processing issues. We will explore three different approaches filter method, forEach Loop, and for Loop to remove empty objects from JSON in JavaScript.

Table of Content

  • Using filter Method
  • Using forEach Loop
  • Using for Loop

Using filter Method

In this approach, we are using the filter method with a callback function to create a new array excluding empty objects based on their key count, making sure only non-empty objects are retained in the filtered array.

Example: The below example uses the filter method to remove empty objects from JSON in JavaScript.

JavaScript
let jArr = [{
    "id": 1,
    "title": "Introduction to Algorithms"
},
{},
{
    "id": 2,
    "title": "Data Structures and Algorithms"
},
{
    "id": 3,
    "title": "Dynamic Programming"
},
{},
];
let res = jArr.filter(obj => Object.keys(obj).length !== 0);
console.log(res);

Output
[
  { id: 1, title: 'Introduction to Algorithms' },
  { id: 2, title: 'Data Structures and Algorithms' },
  { id: 3, title: 'Dynamic Programming' }
]

Using forEach Loop

In this approach, we are using a forEach loop to iterate over the JSON array “jArr” and add non-empty objects to a new array “resby checking their key count, excluding empty objects from the result array.

Example: The below example uses the forEach Loop to remove empty objects from JSON in JavaScript.

JavaScript
let jArr = [{
    "id": 1,
    "title": "Introduction to Algorithms"
},
{},
{
    "id": 2,
    "title": "Data Structures and Algorithms"
},
{
    "id": 3,
    "title": "Dynamic Programming"
},
{},
];
let res = [];
jArr.forEach(obj => {
    if (Object.keys(obj).length !== 0) {
        res.push(obj);
    }
});
console.log(res);

Output
[
  { id: 1, title: 'Introduction to Algorithms' },
  { id: 2, title: 'Data Structures and Algorithms' },
  { id: 3, title: 'Dynamic Programming' }
]

Using for Loop

In this approach, we are using a for loop to iterate over the JSON array “jArr” in reverse order and remove empty objects by checking their key count, using the splice method to modify the array in-place and eliminate empty objects.

Example: The below example uses the for loop to remove empty objects from JSON in JavaScript.

JavaScript
let jArr = [{
    "id": 1,
    "title": "Introduction to Algorithms"
  },
  {},
  {
    "id": 2,
    "title": "Data Structures and Algorithms"
  },
  {
    "id": 3,
    "title": "Dynamic Programming"
  },
  {},
];
for (let i = jArr.length - 1; i >= 0; i--) {
  if (Object.keys(jArr[i]).length === 0) {
    jArr.splice(i, 1);
  }
}
console.log(jArr);

Output
[
  { id: 1, title: 'Introduction to Algorithms' },
  { id: 2, title: 'Data Structures and Algorithms' },
  { id: 3, title: 'Dynamic Programming' }
]