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,716
  • 1
  • 39
  • 59
forgottofly
  • 2,729
  • 11
  • 51
  • 93
  • 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.
  • 76,493
  • 17
  • 173
  • 144
2

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

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