Removing undefined fields from an object in JavaScript

In the following example, we'll remove properties of an object with undefined fields.

The object

We want to remove Bar.category and Bar.revenue properties since both are empty.

javascript
const Bar = {
    
    'category': {},
    'city': 'Barcelona',
    'members': 162000,
    'trophies': {
        'championsLeague': 5,
        'copa': 30
    },
    'revenue': {},
    'sponsors': ['Nike', 'Rakuten', 'Beko', 'CaixaBank']
    
}

The function

We need to loop through the object keys and check whether the value of each property is empty or not.

To know if a property is empty, we need to check if it's an object type and if the length of its keys is equal to zero.

In that case, we'll delete the property:

javascript
Object.keys(Bar).map(key => typeof(Bar[key]) === 'object' && Object.keys(Bar[key]).length === 0 && delete Bar[key]);

Note: checking the type of the property avoids deleting numeric properties as Bar.members = 162000.

Result

javascript
Bar = {
    
    'city': 'Barcelona',
    'members': 162000,
    'trophies': {
        'championsLeague': 5,
        'copa': 30
    },
    'sponsors': ['Nike', 'Rakuten', 'Beko', 'CaixaBank']
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.