Reputation: 1830
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:
i
like [i]
.\i
. (This was probably a stupid idea).+
like, + data.geo_country + i +
.What do I need to do to have i
interpreted properly?
Any help would be greatly appreciated!
Upvotes: 0
Views: 176
Reputation: 29101
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');
}
Upvotes: 2
Reputation: 7947
Access it like
data['geo_country_' + i]
And you should have no issues
Upvotes: 1