0

I have an object like

Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"}

Now i want to remove those keys that have empty values ("").

I tried the code:

 angular.forEach($scope.test,function(value,key){
          if(value==""){
                    var index = $scope.test.indexOf(key);
                    $scope.test.splice(index,1);
          }
  });
//$scope.test={val1: "Hello",val2: "",dt1:".......}

Now there is one more thing that i have to consider the keys are not static. They can change their name depends on the condition. For eg: {val1: "",val2:"Hello1",val3:"",val4:"Hello3",dt1:""} So i need a generic solution.

1 Answers1

0

You can't delete an object property using the splice method. Instead of doing this, you can use the delete operator.

angular.forEach($scope.test,function(value,key){
    if(value==""){
        delete $scope.test[key]
    }
});

For further info regardng this operator, please have a look here. Below I have a snippet with plain JavaScript, that shows the use of delete operator.

var obj = {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"};
console.log('Before we call delete');
console.log(obj);
Object.keys(obj)
      .forEach(function(key){
          if(obj[key]===""){
              delete obj[key];
          }
});
console.log('After we call delete');
console.log(obj);
Christos
  • 53,228
  • 8
  • 76
  • 108