1

like so

► add language identifier to highlight code
fdfsd
```python
def function(foo):
    print(foo)

► put returns between paragraphs

► for linebreak add 2 spaces at end

italic or bold

► indent code by 4 spaces

► backtick escapes like _so_

► quote by placing > at start of line

► to make links (use https whenever possible) https://example.com example example

  • You use a guard, e.g. `var grade = obj[i].Statistics && obj[i].Statistics[i] && obj[i].Statistics[i].Grade;`. There has to be a good dupetarget to point this at, I'll see if I can find one. – T.J. Crowder Jul 07 '19 at 12:56
  • Related: https://stackoverflow.com/questions/6970346/what-is-x-foo – T.J. Crowder Jul 07 '19 at 12:57
  • Beside that error, there are other problems like returning from the loop and using `i` as the index for the inner array. – Titus Jul 07 '19 at 13:00
  • I tried putting the output code outside the loop but it doesn't seem to fix it either –  Jul 07 '19 at 13:02

1 Answers1

0

You need to check for existence of Statistics first before accessing it,

change this

 var grade = obj[i].Statistics[i].Grade;
 var hasPassOrFail = obj[i].Statistics[i].Status;

to this

  var grade = obj[i] && obj[i].Statistics && obj[i].Statistics[0] && obj[i].Statistics[0].Grade;
  var hasPassOrFail = obj[i] && obj[i].Statistics && obj[i].Statistics[0] && obj[i].Statistics[0].Status;

var obj = JSON.parse('[{"Name":"Student1","Id":44844541,"Statistics":[{"Grade":6,"Status":"Pass"}]},{"Name":"Student2","Id":48484848},{"Name":"Student3","Id":99999989,"Statistics":[{"Grade":2,"Status":"Fail"}]}]')

for (var i = 0, len = obj.length; i < len; i++) {

  var grade = obj[i] && obj[i].Statistics && obj[i].Statistics[0] && obj[i].Statistics[0].Grade;
  var hasPassOrFail = obj[i] && obj[i].Statistics && obj[i].Statistics[0] && obj[i].Statistics[0].Status;

  if (grade || hasPassOrFail){
   console.log(grade,hasPassOrFail)
  }
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60