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.
$(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 >' field[0] '</span><br><span >' field[1] '</span><br><span >' 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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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 >' (field[0] ?? 0) '</span><br><span >' (field[1] ?? 0) '</span><br><span >' (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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>