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 trialGabriel Kaunda
12,170 PointsHow exactly does this script add the property values between the lists tags
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var employees = JSON.parse(xhr.responseText);
var statusHTML = '<ul class="bulleted">';
for (var i=0; i<employees.length; i+=1) {
if (employees[i].inoffice === true) {
statusHTML += '<li class="in">';
} else {
statusHTML += '<li class="out">';
}
statusHTML += employees[i].name;
statusHTML += '</li>';
}
statusHTML += '</ul>';
document.getElementById('employeeList').innerHTML = statusHTML;
}
};
xhr.open('GET', 'data/employees.json');
xhr.send();
how does the code above add property values from the JSON to inbetween the lists tags?
1 Answer
Katie Wood
19,141 PointsHi there, The key line here is this one:
statusHTML += employees[i].name;
This is where it adds the "name" value from each entry of the employees object, parsed from JSON on the fourth line of code:
var employees = JSON.parse(xhr.responseText);
This line created a JavaScript object from the JSON, which we called "employees". Then, when creating the list, we take each employee's name property and put it between the tags.
Gabriel Kaunda
12,170 PointsGabriel Kaunda
12,170 PointsstatusHTML += employees[i].name;
So "i" here is the index, and this changes with every run through the loop, which means through every run, the value of name will be different and it will be added to a new list item. Am I correct?
Katie Wood
19,141 PointsKatie Wood
19,141 PointsThat's correct - the loop will increase the index until it is equal to the length of "employees", which will mean they are all printed out.
Gabriel Kaunda
12,170 PointsGabriel Kaunda
12,170 PointsThank you for the answer