Languages
[Edit]
EN

JavaScript - remove empty values from object

3 points
Created by:
Palpys
764

In this article, we would like to show you how to remove empty values from object in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

function removeEmptyValues(object) {
    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            var value = object[key];
            if (value === null || value === undefined || value === '') {
                delete object[key];
            }
        }
    }
}


// Usage example:

var student = {
    name: 'John',
    age: undefined,
    type: null,
    comment: ''
};

console.log(JSON.stringify(student));  // {"name":"John","type":null,"comment":""}

removeEmptyValues(student);

console.log(JSON.stringify(student));   // {"name":"John"}

 

Alternative solution

// ONLINE-RUNNER:browser;

const removeEmptyValues = (object) => {
    const keys = Object.keys(object);
    for (var i = 0; i < keys.length; ++i) {
        const key = keys[i];
        const value = object[key];
        if (value === null || value === undefined || value === '') {
            delete object[key];
        }
    }
};


// Usage example:

const student = {
    name: 'John',
    age: undefined,
    type: null,
    comment: ''
};

console.log(JSON.stringify(student));  // {"name":"John","type":null,"comment":""}

removeEmptyValues(student);

console.log(JSON.stringify(student));   // {"name":"John"}

References

  1. delete operator - JavaScript | MDN 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join