Reputation: 673
I have two condition of my same JSON data:
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[
{
"letterNo":13,
"letterId":1,
"inout":"out",
"inoutNo":"12332466544",
"inoutDate":"2070-01-01",
"letterIssuedSubBy":null,
"letterFile":null,
"representativeName":null,
"representativeNameEng":null,
"selectionId":124,
"assessmentNo":null,
"entryBy":"user98",
"rStatus":"I",
"others":null,
"signatary":"qwerrt",
"letterBox":null,
"imageFile":null,
"imageTitle":null,
"reminderYesNo":"N"
}
]
}
Same JSON with letter array empty structure :
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[]
}
All these values are stored in
var trDataSecondTable; . I tried to compare if the letter
is empty or not by using if condition:
if(trDataSecondTable.letter != null) {
console.log("asasfasdfdsfdsfds");
$("#inoutDate").val(trDataSecondTable.letter[0].inoutDate);
$("#inoutNo").val(trDataSecondTable.letter[0].inoutNo);
$("#signatary").val(trDataSecondTable.letter[0].signatary);
}
else
{
console.log("entered in else part");
}
Though "letter":[]
is empty it is not entering into else part. While comparing i also tried trDataSecondTable.letter.length != 0 but also it is not entering into else part.
Upvotes: 0
Views: 70
Reputation: 13964
Your condition should check for both null
and the length:
if (trDataSecondTable.letter != null && trDataSecondTable.letter.length > 0)
Is is important to check for null
before accessing the length
property as it guarantees you won't try to access the length
property on null
, which would raise an exception. This is important since data is rarely reliable.
Because of the &&
operator, if the first check fails, the second check won't be evaluated.
Actually, an even safer way would be to check if the value is truthy, as this will work for null
and undefined
:
if (trDataSecondTable.letter && trDataSecondTable.letter.length > 0)
Upvotes: 4
Reputation: 2655
I think this condition is enough
if(trDataSecondTable.letter.length)
Upvotes: 0
Reputation: 386560
You could check the length
of the array.
if (trDataSecondTable.letter.length) {
// letter has some elements
} else {
// no elements
}
Upvotes: 1