Search code examples
javascripthtmljqueryjson

Check for Table null in Jquery for JSON response


I have a JSON Response which has 5 tables. So I parse that same JSON. After parsing, I am getting 1st table as [] . So I want to check that condition. Below is the JSON response and parsing.

var dataResponse = JSON.parse(response);
var NE_length_Data = "";
if (dataResponse != null || dataResponse != undefined) {

  var FSAInfoData = dataResponse.Table; // UG
  var FSAInfoData1 = dataResponse.Table1; // MDU
  var FSAInfoData2 = dataResponse.Table2; // AR
  var FSAInfoData3 = dataResponse.Table3; // vendor
  var FSAInfoData4 = dataResponse.Table4; // history
  var FSAInfoData5 = dataResponse.Table5; // progress data

  $("#spnFiberEngFsaId").text(FSA_IDNew);
  $("#spnProgressID").text(FSAInfoData5[0].JOB_PROGRESS_ID);

  var NE_LENGTH = FSAInfoData[0].UG_LENGTH + FSAInfoData2[0].AR_LENGTH; // Here I want to add condition to check null for 1st table
  $("#spnFiberEngFsaLength").text(NE_LENGTH.toFixed(4));

}

Due to this null not checked my code is not getting further executed. Please help


Solution

  • Check the length before trying to index into the array.

    var NE_LENGTH = (FSAInfoData.length == 0 ? 0 : FSAInfoData[0].UG_LENGTH) + FSAInfoData2[0].AR_LENGTH;
    

    So if the length of the first table is 0, this defaults to 0 instead of FSAInfoData[0].UG_LENGTH.

    Another method is to use optional chaining to prevent the error when trying to access the property of a nonexistent element, and ?? to supply the default value.

    var NE_LENGTH = (FSAInfoData[0]?.UG_LENGTH ?? 0) + FSAInfoData2[0].AR_LENGTH;