0

I'm trying to create a for() loop with JSON data that's already been decoded, the problem is adding my loop variable (in this case i), to the end of the element that I'm referencing.

For example, my JSON structure, dumped:

{
    "url": "http://www.example.com",
    "rid": 1,
    "rname": "Apple iPhone 4 Rotation",
    "rmin": 90,
    "rmax": 150,
    "blank": 0,
    "geo_country_0": "GB",
    "geo_url_0": "http://en",
    "geo_country_1": "FR",
    "geo_url_1": "http://fr",
    "geo_country_2": "ES",
    "geo_url_2": "http://es"
}

In the case of geo_country_ and and geo_url_ I need to append a number, in this case the loop variable.

My actual for loop, for a better understanding:

for(i = 1; i < count; i++) {
                $('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data.geo_url_i+ '"/></div>');
                $('select[name="g_country['+i+']"').find('option[value="' + data.geo_country_i+ '"]').attr('selected','selected');
            }

So far I've tried:

  • Encasing the the i like [i].
  • Escaping it like \i. (This was probably a stupid idea).
  • Adding a pre-fixing + like, + data.geo_country + i +.

What do I need to do to have i interpreted properly?

Any help would be greatly appreciated!

1
  • Are you trying to reference data.geo_country_? like data['geo_country_'+i]? Commented Oct 15, 2011 at 3:01

2 Answers 2

2

In JavaScript, you may address an object's properties in two ways:

var value = myobject.myproperty;
var value2 = myobject['myproperty'];

Using this knowledge, you can rewrite your code as follows:

        for(i = 1; i < count; i++) {
            $('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data['geo_url_' + i] + '"/></div>');
            $('select[name="g_country['+i+']"').find('option[value="' + data['geo_country_' + i] + '"]').attr('selected','selected');
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Props, for both the edit, and the explanation. I'll accept when the timer drops :)!
1

Access it like

data['geo_country_' + i]

And you should have no issues

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.