checking an object for null element

100 Views Asked by At

The response from a http GET method is as shown below:

{
  id:1,
  name:"John",
  subjects:[],
  totalMarks:458
}

In the front end I want to check whether the subjects property is empty or not. I have tried with this approach but not working

var newObj= {
    id:1,
    name:"John",
    subjects:[],
    totalMarks:458
}

if (newObj.subjects == null) {
  alert("Empty subjects");
}
2

There are 2 best solutions below

0
On BEST ANSWER

newObj.subjects is Array, so you need check it like this

if(Array.isArray(newObj.subjects) && !newObj.subjects.length) {
   alert("Empty subjects");
}
0
On

You can use length property to check if the array is empty..

 if(newObj.subjects.length==0)
    {
       alert("Empty subjects");
    }