tags:

views:

33

answers:

2

Hi, 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.

+3  A: 

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.

Josh Stodola
**Note:** You *can* dynamically reach lower-level properties with syntax similiar to that of multi-dimensioned arrays. For example: `var num = window['obj']['pract_' + i];`
Josh Stodola
Thank you, that's exactly what I needed
The_Denominater
A: 
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.

just somebody