Let’s say the following is our object −
const details = { name: 'John', age: {}, marks: { marks: {} } }
We need to remove the black objects above You can use forEach() along with typeof and delete to remove blank objects.
Example
Following is the code −
const details = { name: 'John', age: {}, marks: { marks: {} } } function removeAllBlankObjects(detailsObj) { Object.keys(detailsObj).forEach(k => { if (detailsObj[k] && typeof detailsObj[k] === 'object' && removeAllBlankObjects(detailsObj[k]) === null) { delete detailsObj[k]; } }); if (!Object.keys(detailsObj).length) { return null; } } removeAllBlankObjects(details); console.log(details);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo283.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo283.js { name: 'John' }