Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jackie Jen
2,723 Pointshow to auto increment property name through looping method
let siad i have objectName[propertyName] as below
{"visited1":"106","visited2":"107","visited3":"104"}
how to use looping to access the property name. Below is my code which cannot access the property name by using looping. it gave me undefined
var country = {"visited1":"106","visited2":"107","visited3":"104"};
for (i=1; i<3; i++){
$('#viewer' +i).append('<tr><td id="viewer"+i>'+country.visited+i+'</td></tr>');
}
Please advice
1 Answer
Jamie Weir
4,241 PointsTry replacing country.visited+i with country["visited"+i]. This is another way to call a value from an object.
If you don't need anything more complex than an ordered series of values, you could also use an array instead of an object, such as var countryvisited = ["106","107","104"] And then call it in the loop with countryvisited[i].
Just make sure you start the counter from 0 if you are using an array.
Iain Simmons
Treehouse Moderator 32,305 PointsIain Simmons
Treehouse Moderator 32,305 PointsAlso, the current loop with a JavaScript object will only run through twice, and won't include the third key/value in the object.
It should be either
i < 4ori <= 3βsorry, no love heart in this case! :)Jackie Jen
2,723 PointsJackie Jen
2,723 PointsThanks Jamie & Simmons.
It works!!