23

I am using jsPdf. When a field has been left blank "undefined" is printed on the pdf. I would like to replace that with a empty string. I am trying to use a if statement but I am not getting it.

 doc.text(30, 190, "Budget : $");
    if ($scope.currentItem.JobOriginalBudget == "undefined") {

        doc.text(50, 190, " ");
    }
    else {
        var y = '' + $scope.currentItem.JobOriginalBudget;
        doc.text(50, 190, y);
    };
texas697
  • 5,609
  • 16
  • 65
  • 131
  • 2
    Just do `var value = $scope.currentItem.JobOriginalBudget || " "; doc.text(50, 190, value+'') ` Check for falsy value which could be `undefined, "", null, NaN, false, 0` etc.. Or use `angular.isUndefined($scope.currentItem.JobOriginalBudget)` for specific check, or even `angular.isDefined` for the opposite of previous – PSL Sep 16 '14 at 18:52
  • or expanding on what @PSL shows, create a simple helper function since a PDF likely has numerous of these to do and can write `getVal(var)` a lot easier than lots of comparisons – charlietfl Sep 16 '14 at 18:57
  • `var y = '' + ($scope.currentItem.JobOriginalBudget || '');` – Jason Goemaat Sep 16 '14 at 20:24

6 Answers6

21

As per this answer I believe what you want is

doc.text(50, 190, $scope.currentItem.JobOriginalBudget || " ")
Community
  • 1
  • 1
Nuno Costa
  • 1,210
  • 11
  • 12
15

undefined is a primitive value. Instead of comparing against the identifier undefined, you're comparing against the 9-character string "undefined".

Simply remove the quotes:

if ($scope.currentItem.JobOriginalBudget == undefined)

Or compare against the typeof result, which is a string:

if (typeof $scope.currentItem.JobOriginalBudget == "undefined")
apsillers
  • 112,806
  • 17
  • 235
  • 239
3

var ab = {
firstName : undefined,
lastName : undefined
}

let newJSON = JSON.stringify(ab, function (key, value) {return (value === undefined) ? "" : value});

console.log(JSON.parse(newJSON))
<p>
   <b>Before:</b>
   let ab = {
   firstName : undefined,
   lastName : "undefined"
   }
   <br/><br/>
   <b>After:</b>
   View Console
</p>
Abdullah
  • 2,393
  • 1
  • 16
  • 29
2

simply remove the "== 'undefined'"

if (!$scope.currentItem.JobOriginalBudget) {
    doc.text(50, 190, " ");
}
theDarse
  • 749
  • 5
  • 13
1

If item is an Object use, this function :

replaceUndefinied(item) {
   var str =  JSON.stringify(item, function (key, value) {return (value === undefined) ? "" : value});
   return JSON.parse(str);
}
Maxime
  • 643
  • 10
  • 21
0

In my case

doc.text(50, 190, $scope.currentItem.JobOriginalBudget??"")
Ruslan Novikov
  • 1,320
  • 15
  • 21