
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
How to remove all blank objects from an Object in JavaScript?
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' }
- Related Articles
- How to remove blank (undefined) elements from JavaScript array - JavaScript
- Remove number properties from an object JavaScript
- Remove all objects from the Queue in C#
- Remove all objects from the Stack in C#
- MongoDB query to remove empty objects in an object-array?
- How to remove an object using filter() in JavaScript?
- The best way to remove duplicates from an array of objects in JavaScript?
- Converting array of objects to an object of objects in JavaScript
- How to remove a property from a JavaScript object?
- How to remove an object from a list in Python?
- How to remove a parameter from all Request Objects at Controller Level in Laravel?
- Converting array of objects to an object in JavaScript
- How to remove all the elements from a set in javascript?
- How to remove all the elements from a map in JavaScript?
- How to import an Object with Sub Objects and Arrays in JavaScript?

Advertisements