Reputation: 995
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.
Upvotes: 1
Views: 1171
Reputation: 19247
for (var p in obj) {
var pract = obj[p];
if (???) {
$('#'+p).attr('checked', 'checked');
}
}
what you're doing around pract_num
seems broken or misguided, at least without additional context.
Upvotes: 0
Reputation: 82483
Just reference obj
directly instead of going through window
...
var obj = window['myObj']; // if needed
for (var i = 0; i < 10; i++) {
var pract_num = ++obj['pract_' + i]; // magic
if (pract_num == 1) {
var pract = '#pract_' + i;
$(pract).attr('checked', 'checked');
}
}
You are getting NaN
because you try to increment (++
) a reference to something non-numeric.
Upvotes: 3