Reputation: 37
Sorry if im posting wrong, first time using stackoverflow. but I am having trouble appending my work objects to my page. its on the page but coming up as undefined. here is my code
var work = {
"jobs": [{
"employer": "Marco Polo",
"title": "Waiter",
"location": "East Hartford,CT",
"dates": "2012 to present",
"description": "Serves tables and cleans up after restaurant"
}
]
};
work.display = function () {
work.jobs.forEach(function (job) {
console.log(job);
$("#workExperience").append(HTMLworkStart);
formattedEmployer = HTMLworkEmployer.replace("%data%", work.jobs.employer);
formattedTitle = HTMLworkTitle.replace("%data%", work.jobs.title);
var formattedEmployerTitle = formattedEmployer + formattedTitle;
$(".work-entry:last").append(formattedEmployerTitle);
formattedworkLocation = HTMLworkLocation.replace("%data%", work.jobs.location);
$(".work-entry:last").append(formattedworkLocation);
formattedworkDates = HTMLworkDates.replace("%data%", work.jobs.dates);
$(".work-entry:last").append(formattedworkDates);
formattedworkDescrip = HTMLworkDescription.replace("%data%", work.jobs.description);
$(".work-entry:last").append(formattedworkDescrip);
});
};
Upvotes: 0
Views: 90
Reputation: 1696
(Sincerest apologies if this is malformed or misinformed. First post, please be kind; any guidance from the community towards a better answer would be much appreciated)
I believe the issue lay in your forEach loop. Inside of the forEach loop "job" will reference the current iteration from work.jobs. Therefore instead of referencing work.jobs.employer, it should be referenced by job.employer. The reason you were getting undefined is because you were attempting to retrieve employer/title/location/etc from the jobs array, not the objects contained within the array.
Please try the below:
work.jobs.forEach(function(job) {
console.log(job);
$("#workExperience").append(HTMLworkStart);
formattedEmployer = HTMLworkEmployer.replace("%data%",job.employer);
formattedTitle = HTMLworkTitle.replace("%data%",job.title);
var formattedEmployerTitle = formattedEmployer + formattedTitle;
$(".work-entry:last").append(formattedEmployerTitle);
formattedworkLocation = HTMLworkLocation.replace("%data%",job.location);
$(".work-entry:last").append(formattedworkLocation);
formattedworkDates = HTMLworkDates.replace("%data%",job.dates);
$(".work-entry:last").append(formattedworkDates);
formattedworkDescrip = HTMLworkDescription.replace("%data%",job.description);
$(".work-entry:last").append(formattedworkDescrip);
});
Upvotes: 0
Reputation: 816
Your code is iterating over the jobs array, but the array only has a single element - an object with job information. If you want to iterate over that information (employer, title, location, etc) you need to use a for...in loop (which iterates over objects) after indexing into the array.
for (var prop in work.jobs[0]) { ...}
Upvotes: 1