1

I'm trying to get the value "0" back when there's nothing written in the spreadsheet cell whose data I get returned as JSON in an API call. But the output is always undefined. I tried using if else, but it didn't work.

IMG SHEET

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + field[0] + '</span><br><span class="field2">' + field[1] + '</span><br><span class="field3">' + field[2] + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color:green;
}
.field2 {
  font-size: 14px;
  color:blue;
}
.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

1 Answer 1

3

You can use the ?? operator (Nullish coalescing operator) to replace null and undefined with something else, in this case, 0.

For example: (field[1] ?? 0)

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + (field[0] ?? 0) + '</span><br><span class="field2">' + (field[1] ?? 0) + '</span><br><span class="field3">' + (field[2] ?? 0) + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color: green;
}

.field2 {
  font-size: 14px;
  color: blue;
}

.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Ohh it worked perfectly. And in place of "0" would it be possible to return a " - " or " " too? Does it follow the same logic?
I linked the documentation, but yes. If on the left side of ?? you have null or undefined, it will be replaced with the right side. You can put whatever you want to :)
Got it, thank you very much for the teachings. :DD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.