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
Lance Manchester
Courses Plus Student 115 Pointsajax json multilevel
I got this to work for some reason, but because I don't know what happened, I tried a different approach but when I want to revert it to the working code, It gave me undefined.
can someone point out where I've gone wrong....
$.getJSON('js/file.json',function(result){
var output = "<ul>";
$.each(result,function(index, value){
console.log(value);
output += "<li>" + value.firstName + "</li>";
}); //end each
output += "</ul>";
$("#js-result-list").html(output);
}); //end getJSON
JSON
{ "users":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"joined": {
"month":"January",
"day":12,
"year":2012
}
},
{
"firstName":"John",
"lastName":"Jones",
"joined": {
"month":"April",
"day":28,
"year":2010
}
}
]
}
2 Answers
Dave McFarland
Treehouse TeacherIn your first example, the JSON file is an object containing a single property, "users", which is an array. So the result variable will be that object. You could re-write the JavaScript like this:
$.getJSON('js/file.json',function(result){
var output = "<ul>";
$.each(result.users,function(index, value){
console.log(value);
output += "<li>" + value.firstName + "</li>";
}); //end each
output += "</ul>";
$("#js-result-list").html(output);
}); //end getJSON
Notice that I don't pass the result variable to $.each. I pass result.users which is the array of users in the JSON file.
Lance Manchester
Courses Plus Student 115 Pointsyah I figured it out after a few tries. btw you're the guy in the video. what an honor, I like the course. good job!
Dave McFarland
Treehouse TeacherGlad you like the course!
Lance Manchester
Courses Plus Student 115 PointsLance Manchester
Courses Plus Student 115 Pointsnvm, I got it. i just add the index or the first level object to my result. like this.