2

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");
}
a--m
  • 4,536
  • 1
  • 34
  • 53
forgottofly
  • 2,639
  • 10
  • 45
  • 87
  • will `subjects` be always an Array? Will always be defined? – a--m Dec 22 '14 at 08:39
  • 1
    possible duplicate of [Check if array is empty or exists](http://stackoverflow.com/questions/11743392/check-if-array-is-empty-or-exists) – a--m Dec 22 '14 at 08:43
  • 1
    The answer to your problem is there: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons/359509#359509 – ddaa Dec 22 '14 at 11:11

2 Answers2

3

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

if(Array.isArray(newObj.subjects) && !newObj.subjects.length) {
   alert("Empty subjects");
}
Oleksandr T.
  • 73,526
  • 17
  • 164
  • 143
2

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

 if(newObj.subjects.length==0)
    {
       alert("Empty subjects");
    }
Sampath Liyanage
  • 4,618
  • 25
  • 40