How to Remove Empty Values from a JSON Object in Javascript?

Nov 15, 2022 . Admin



Hello friends,

This simple article demonstrates how to remove empty values from a JSON object in javascript. Now, let's see the article of remove empty values from objects in javascript. I would like to show you how to remove all empty values from an object.

To remove empty values, use the for...in the loop to iterate over the object. On each iteration, check if the value is equal to an empty string. If the condition is met, use the delete operator to delete the key-value pair.

So, let's see bellow solution:

Example:
index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>How to Remove Empty Values from a JSON Object in Javascript?</title>
</head>
<body>
<script type="text/javascript">
   
    //create testPlayer   
    const testPlayer = {
        Name: 'Shikhar Dhawan',
        Age: ' ',
        Team: ' ',
    };

    //loop to iterate over the object
    for (const key in testPlayer) {
        if (testPlayer[key] === '') {
            delete testPlayer[key];
        }
    }

    //print removed empty values
    console.log(testPlayer);

</script>
</body>
</html>
Check The Console For Output:
{Name: 'Shikhar Dhawan'}

I hope it will help you...

#Javascript