How Can I Check If A Variable In An Array In An Array In An Array Is Defined And Not Null?
I am trying to check to see if wordDefinitionId is defined and not null. Here's what I have been trying to do but think even this code seems to give some problems. Is there an ea
Solution 1:
Use &&
(AND) logical operator between conditions, if first condition fails second condition will not check and so on
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId
var wos = {
word: {
"wordId": "tyyyyyy",
"wordIdentity": 160,
"ascii": 116,
"categoryId": 1,
"groupId": 1,
"lessonId": 1,
"ielts": null,
"toefl": true,
"toeic": null,
"wordForms": [{
"wordFormId": "qwqwqwqwq",
"wordFormIdentity": 145,
"ascii": 113,
"wordId": "tyyyyyy",
"primary": false,
"posId": 1,
"sampleSentences": [],
"synonyms": [],
"wordDefinitions": [{
"wordDefinitionId": 142,
"wordFormId": "qwqwqwqwq",
"text": "wrwrwrwrwr",
"ascii": 119
}],
"pos": null,
"version": "AAAAAAAADn0=",
"createdBy": 2,
"createdDate": "2016-05-03T13:23Z",
"modifiedBy": 2,
"modifiedDate": "2016-05-03T20:23Z"
}],
"lesson": null,
"wordCategory": null,
"wordGroup": null,
"version": "AAAAAAAADf4=",
"createdBy": 2,
"createdDate": "2016-05-03T13:23Z",
"modifiedBy": 2,
"modifiedDate": "2016-05-03T20:23Z",
"current": true
}
};
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionIddocument.write('<pre>' + JSON.stringify(wos, 0, 3) + '</pre>');
Solution 2:
You don't reach the third if, because in your second if
statement, the wos.word.wordForms[0].synonyms
will evaluate to true as it is defined and is an empty list. You can check it yourself:
if (wos.word.wordForms[0].synonyms) { alert('Yes!'); } // will alert 'Yes!'
But right next to it, you try to access wos.word.wordForms[0].synonyms[0]
, which does not exist, hence the TypeError: wos.word.wordForms[0].synonyms[0] is undefined
. The same situation is with your wos.word.wordForms[0].sampleSentences
In order to fix this, check the length of the list as well:
if (wos.word.wordForms
&& wos.word.wordForms[0].synonyms
&& wos.word.wordForms[0].synonyms.length // <-- check for element existence
&& wos.word.wordForms[0].synonyms[0].synonymId) {
...
}
Post a Comment for "How Can I Check If A Variable In An Array In An Array In An Array Is Defined And Not Null?"