Skip to content Skip to sidebar Skip to footer

Printing A Selection Of A Json Array Data Out To A Page Using Jquery

Not having much luck with a tricky JSON object and getting it to write certain data into a HTML page. I am attempting to target only particular sets of data in the array - not the

Solution 1:

What you need to do is first iterate the nested JSON and group together the information for each room like this:

// loop over the objectand gather all the information for each room type  
var bookingsByRoom = {};
$.each(response.bookings.timeslots, function(i, timeslot) {
  var room = timeslot.room_name;
  if (bookingsByRoom[room]) bookingsByRoom[room].push(timeslot);
  else bookingsByRoom[room] = [timeslot];
});
/*
bookingsByRoom is now an object like:
{
  Meeting Room 2 A: {
    booking_end: "2016-01-20T11:00:00+10:00",
    booking_label: "Mahjong"
    booking_start: "2016-01-20T10:00:00+10:00"
    room_id: "36615"
    room_name: "Meeting Room 2A"
  }, {
    booking_end: "2016-01-20T12:00:00+10:00"
    booking_label: "Mahjong"
    booking_start: "2016-01-20T11:00:00+10:00"
    room_id: "36615"
    room_name: "Meeting Room 2A"
  }
}, 
{
  Meeting Room 2 B: ....
}

*/

Then you can loop over the newly created array and display whatever data you need.

Here is a jsFiddle showing how you might further this to actually display your data.

Solution 2:

I made javascript code

// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",

// The name of the callback parameter, as specified by the YQL servicejsonp: "callback",

// Tell jQuery we're expecting JSONPdataType: "jsonp",

// Work with the responsesuccess: function( response ) {
        console.log(response);
    var data = response.bookings.timeslots;
    var room  = {};
    var roomInfo = {};

    $.each(data, function(index,element){
        if(typeof room[element.room_id] === "undefined"){
        room[element.room_id] = [];
        roomInfo[element.room_id] = element.room_name;
      }
      room[element.room_id].push(element);
    });




    for(var roomId in room){
        var dest = room[roomId];
      var tr = $('<tr>');
      tr.append($('<td>'+roomInfo[roomId]+'</td>'));
      var td = $('<td>');
      for(var i=0; i<dest.length; i++){
        var item = dest[i];
        var div = $('<div></div>');
        div.text(item.booking_label+" ["+item.booking_start+" : "+item.booking_end+"]");
        td.append(div);
      }

      tr.append(td);

      $("table").append(tr);
    }

}
});

My Practice Code

Post a Comment for "Printing A Selection Of A Json Array Data Out To A Page Using Jquery"