How to Remove Empty Object From JSON in JavaScript

In this post, we have removed empty objects in JSON using Javascript. It is a very simple code snippet to remove all empty objects in JSON.

<DOCTYPE html>
<html>
<head>
    <title>How to remove empty object from json in javascript</title>
</head>
<body>
   
<script type="text/javascript">
   
    const objectData= { 
      b:'object',
      c: '',
      d: null,
      f: {v: 2, x: '', y: null, m: {a:'xyz'}}
    };
   
    const removeEmptyOrNullObject = (obj) => {
      Object.keys(obj).forEach(k =>
        (obj[k] && typeof obj[k] === 'object') && removeEmptyOrNullObject(obj[k]) ||
        (!obj[k] && obj[k] !== undefined) && delete obj[k]
      );
      return obj;
    };
   
    finalData = removeEmptyOrNullObject(objectData);
   
    console.log(finalData);
</script>
</body>
</html>

Output

How to Remove Empty Object From JSON in JavaScript example

Spread the love

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *