Search code examples
javascriptarraysarraylistarrayobject

checking an object for null element


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");
}

Solution

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

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