samuel toh samuel toh - 6 months ago 12
HTML Question

How to display json object to html?

My Json Object is like this :

[{
"attributes": {
"Code": "SGL",
"Total": "19421340.27"
},
"DayPrice": [{
"Date": "2016-07-22",
"Rate": "4900439.85"
}, {
"Date": "2016-07-23",
"Rate": "4845150.21"
}, {
"Date": "2016-07-24",
"Rate": "4845150.21"
}, {
"Date": "2016-07-25",
"Rate": "4830600"
}]
}, {
"attributes": {
"Code": "DBL",
"Total": "6473780.09"
},
"DayPrice": [{
"Date": "2016-07-22",
"Rate": "1633479.95"
}, {
"Date": "2016-07-23",
"Rate": "1615050.07"
}, {
"Date": "2016-07-24",
"Rate": "1615050.07"
}, {
"Date": "2016-07-25",
"Rate": "1610200"
}]
}, {
"attributes": {
"Code": "QUAD",
"Total": "6473780.09"
},
"DayPrice": [{
"Date": "2016-07-22",
"Rate": "1633479.95"
}, {
"Date": "2016-07-23",
"Rate": "1615050.07"
}, {
"Date": "2016-07-24",
"Rate": "1615050.07"
}, {
"Date": "2016-07-25",
"Rate": "1610200"
}]
}]


From the json object array, I want display like this image:

enter image description here

I had try it, but I'm still confused.
I feel it can not be done.

I try loop in loop like this :

countRoomType = json_object.length;
for(var i=0; i<countRoomType; i++){
countDayPrice = json_object[i].DayPrice.length;
for(var j=0; j<countDayPrice; j++){
...
}
}


Any solution to solve my problem?

Answer

You can use for loop to iterate through the object.

UPDATE

Check this FIDDLE

// Create a new blank object
var dateObj = {};

// Iterate original object
for (key in json_object) {
  var obj = json_object[key];
  var day = obj.DayPrice;
  for (dt in day) {
    var dtObj = day[dt];
    var dtKey = dtObj.Date;    
    if (dateObj.hasOwnProperty(dtKey)) {
        dateObj[dtKey].push({ Code: obj.attributes.Code, Rate: dtObj.Rate });
    } else {
        dateObj[dtKey] = [{ Code: obj.attributes.Code, Rate: dtObj.Rate }];
    }
  }
}

// Iterate the newly created object
for(d in dateObj) {
    var obj = dateObj[d];
    var row = '<tr><td>' + d + '</td><td><ul>';
  $.each(obj, function(i, val) {
    console.log(val);
    row += '<li>' + val.Code + ': ' + val.Rate + '</li>';
  });
  row += '</ul></td></tr>';
  $('#target').find('tbody').append(row);
}