A
A
Angry Negro2020-11-23 10:14:16
JavaScript
Angry Negro, 2020-11-23 10:14:16

How to handle Undefined in JSON (Ajax jquery)?

Hello! This problem haunts me for what a sleepless night I've lost count of:
There is a JSON code for processing the response, everything is classic:

function result(data){
      if(data != null){
          api_loan_amount = data.noticeInfo.document; // Сумма займа
          api_expirationDate = data.applSubmissionCloseTime; // Дата окончания приема заявок
      } else {
      }
     }


I process it all - I get a response, etc. But here's the catch - today data.noticeInfo.document is there - tomorrow it isn't, but then data.applSubmissionCloseTime . As you understand, the answer may not contain array elements. And it gives me an Undefined error as a result and interrupts my processing of getting other fields.
I dug up a bunch of information about usage by type:
if(typeof data.noticeInfo.document === undefinded){
 // Вот тут обрабатываем ошибку в теории
}


Everything would be fine, but in this case, if there is no data.noticeInfo.document , then Undefinded gives an error in the line where the logical operator itself is in if, because I am checking what Undefinded is and gives me an error as a result .. Question :

How can I ignore this damned Undefinded ? It's better to know how to handle it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2020-11-23
@alexalexes

If you always have a data.noticeInfo object, but sometimes the document property is missing, then you can check for the presence like this:

if('document' in data.noticeInfo)
{
}

or so, if you need to distinguish between prototype-conditioned properties and pre-assigned properties:
if(data.noticeInfo.hasOwnProperty('document'))
{
}

If the property is deep, and it’s too lazy to check the existence of a chain of properties / objects before it, without getting a debugger warning, or the entry is too cumbersome, then you need an analogue of the isset function from PHP for JS .
if(typeof data.noticeInfo.document != "undefined" && data.noticeInfo.document !== null)
{
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question