I’m trying to iterate through a bunch of variables in a javascript (using jQuery) object that was returned through JSON, without having to specify each variable name.
What I want to do is loop through the following elements of an object and test their values:
obj.pract_0
obj.pract_1
obj.pract_2
obj.pract_3
..
..
obj.pract_100
The approach I am trying is the following:
for (var i = 0; i < 10; i++) {
var pract_num = ++window['obj.pract_' + i];
if (pract_num == 1) {
var pract = '#pract_' + i;
$(pract).attr('checked', 'checked');
}
}
I’m getting NaN from this though, is there another way to do this? My problems are obviously from var pract_num = ++window['obj.pract_' + i]; and I’m not sure if I’m doing it correctly.
I’d rather not have to modify the code that generates the JSON, though I’m not quite sure how I’d do it.
Just reference
objdirectly instead of going throughwindow…You are getting
NaNbecause you try to increment (++) a reference to something non-numeric.