1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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];
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.