Luiz Alves
Luiz Alves

Reputation: 2645

Unable to delete empty object properties with javascript and angular

I am using angular 1.6.

I need remove some properties of a javascript object if they are null, empty or undefined.

In my case, i have two empty arrays 'byweekday" and "bymonth" and I am trying to delete them from object, without success.

What am I doing wrong?

//markup

<button class="btn btn-xs btn-success" type="button" 
                     ng-click="makecalc()">
                     Calculate
</button>

//code

//angular controller

     $scope.repeticao={"wkst":1,"freq":{"id":0,"name":"Anualmente"},"byweekday":
   [],"bymonth":[]};

    function removeEmpty(obj) {
      Object.keys(obj).forEach(function(key) {
        if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key])
        else if (obj[key] === null || obj[key] === undefined) delete obj[key]
      });
      return obj;
    };
    $scope.makecalc=function(){
          //debugger;
          var key, value, date;
          var values = angular.copy($scope.repeticao);
          values=removeEmpty(values);
          console.log(JSON.stringify(values)); 
    }

Upvotes: 0

Views: 217

Answers (1)

rgthree
rgthree

Reputation: 7273

Your code only deletes a key when the value is null or undefined so, obviously, it won't delete an empty array, so you'll need to check for that as well. Since typeof is also "object" you'll need to check for a removable-item first. (Also, using == with null checks for both null and undefined, so we can simplify that as well):

function removeEmpty(obj) {
  Object.keys(obj).forEach(function(key) {
    if (obj[key] == null || (Array.isArray(obj[key]) && obj[key].length === 0)) {
      delete obj[key];
    } else if (typeof obj[key] === 'object') {
      removeEmpty(obj[key]);
    }
  });
  return obj;
};

Upvotes: 2

Related Questions