How to remove empty values from json object in javascript (jQuery)

Throughout this jquery remove empty values from json object example tutorial you will learn how to remove empty, blank, null values from json object javascript (js) jquery library.

Here we have added two easy and simple example of remove null, undefined, emplty values in json using javascript. Let’s see the best example to understand for remove all null values in javascript (jQuery).

Solution 1:

<script type="text/javascript">
   
    const testObject = { 
      b:'my object',
      c: '',
      d: null,
      f: {v: 1, x: '', y: null, m: {a:'asd'}}
    };
   
    const removeEmptyOrNull = (obj) => {
      Object.keys(obj).forEach(k =>
        (obj[k] && typeof obj[k] === 'object') && removeEmptyOrNull(obj[k]) ||
        (!obj[k] && obj[k] !== undefined) && delete obj[k]
      );
      return obj;
    };
   
    newObject = removeEmptyOrNull(testObject );
   
    console.log(newObject );
</script>

Solution 2:

var test = {
  test1: null,
  test2: 'somestring',
  test3: 3,
}

function clean(obj) {
  for (var propName in obj) {
    if (obj[propName] === null || obj[propName] === undefined) {
      delete obj[propName];
    }
  }
  return obj
}

console.log(test);
console.log(clean(test));

I hoep these examples help you.

Leave a Comment