0

I am totally stuck, I am sure the problem is small but I can't get my mind around it. I can't find a way to display the content that I get from the Array correctly. I have searched SO but couldn't find any correct answers.

Here is the JSON:

{
"rooster": {
  "weekdag": {
         "1": {
           "uur": {
               "1": {
                   "teacher": "EVDIS",
                   "subject": "ENG",
                   "room": "312"
},

To explain it a little further, weekdag contains 5 Objects that represent the day of the week. Within that is an Object called uur. It represents an hour. Each day contains 10.

The code that is currently used to display all of the data:

$.ajax({
    type: "GET",
    dataType: "json",
    url: '/c00012.json',
    success: function (data) {
        //Sort of displays the schedule
        $.each(data.rooster.weekdag[1].uur, function() {
            $.each(this, function(name, value) {
                document.write(value);
            });
        });
    }
});

It displays this:

ENGEVDIS312ENGEVDIS312SDEMONK308SDEMONK308

So, what I want to achieve is to print it out like this:

Hour 1: Teacher: EVDIS
        Subject: ENG
        Room: 312
Hour 2: Teacher: EVDIS
        Subject: ENG
        Room: 312

I might have explained it a bit weird, if any other information is needed let me know.

indubitablee
  • 7,636
  • 2
  • 22
  • 48
LJ Dev
  • 13
  • 3
  • Just as a heads up, you definitely **don't** want to use `document.write` once an async request finishes long after the page has finished it's initial load, see this question: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Etheryte Sep 08 '15 at 16:00
  • I assume you want this as formatted HTML, not just values printed on a page. The best option would be to use templates. Have a search around for jquery templates. – codemonkey Sep 08 '15 at 16:03
  • name should hold the keys like "Teacher", "Subject", etc ( $.each(this, function(name, value) { ). You're currently only using value. – devlin carnate Sep 08 '15 at 16:05

2 Answers2

1

Instead of looping through the uur object properties, get the specific properties. Example:

$.ajax({
  type: "GET",
  dataType: "json",
  url: '/c00012.json',
  success: function (data) {
    //Sort of displays the schedule
    $.each(data.rooster.weekdag[1].uur, function(h, obj) {
      document.write(
        'Hour ' + h + ': Teacher: ' + obj.teacher + '<br>' +
        'Subject: ' + obj.subject + '<br>' +
        'Room: ' + obj.room
      );
    });
  }
});
Guffa
  • 640,220
  • 96
  • 678
  • 956
0
 $.each(this, function(name, value) {
  for(int i = 0; i<value.length; i++)
   {
     var result = "Hour " + (i+1) + ": Teacher: " value[i].teacher + \n +
     "Subject: " + value[i].Subject + \n +
     "Room: " + value[i].Room;
   }
});

This is quickly written but you will get the point I believe

Zoran P.
  • 800
  • 1
  • 11
  • 16