0

I have JSON array similar to this :

{"X":[
    {"Time":"05:45","Count":70},
    {"Time":"06:30","Count":40},
    {"Time":"08:15","Count":80}
]},
{"Y":[
    {"Time":"09:15","Count":70},
    {"Time":"10:30","Count":84},
    {"Time":"12:00","Count":95}
]},
{"Z":[
    {"Time":"14:00","Count":80},
    {"Time":"16:00","Count":70},
    {"Time":"15:00","Count":40}
]}

I have to populate table like this dynamically :

Name    05:45   06:30   08:15   09:15   10:30   12:00   14:00   16:00   15:00

  X       70      40       80     0       0       0       0       0       0
  Y        0       0        0     70     84       95      0       0       0 
  Z        0       0        0     0       0       0       80      70      40

I don't know how to populate this as Javascript table. Could anyone please help me with this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Priya
  • 591
  • 1
  • 8
  • 23
  • _"how to populate this as javascript table"_ `html` `` element ? `json` appear to have syntax error ? , are objects within array ?
    – guest271314 Sep 09 '15 at 04:31
  • Objects are within array – Priya Sep 09 '15 at 04:40
  • What have you tried? Hard to help with no code. Look over this similar question for some hints: http://stackoverflow.com/questions/18846253/how-do-i-create-html-table-using-jquery-dynamically – Georgette Pincin Sep 09 '15 at 04:40

4 Answers4

1

Use JSON.parse(//your json string). Now you can dynamically create rows by looping through this json array something like this--

 var DataArray = JSON.parse(data.d);
      var tableelement = $("#DataSetTbl");        //get table id from jquery

        tableelement.append(createRow(DataArray));            //call this function from the action you want to show table

    function createRow(Object) {                              //dynamically adding rows to the Table

        var trElement = "<tr>";                 //design this according to your requirement

  for(var s=0;s<Object.length; s++)
        trElement += "<td >" + Object[s].Time + "</td>";


        return trElement;
    }

Similarly append a new row for count :)

AkshayJ
  • 771
  • 6
  • 15
  • This won't work as expected becuase there are 9 columns in this case and this code will only generate 3. :) – AdityaParab Sep 09 '15 at 04:55
  • I just showed a sample by creating 3 columns.You can create 9 columns by accessing the array indexes as desired :) – AkshayJ Sep 09 '15 at 04:57
  • That only seems to be the central question! How do you access all the properties in a single loop (preferably). :) – AdityaParab Sep 09 '15 at 04:58
1

Try creating valid json array of objects , utilizing $.each() , .after() , Object.keys() ; table , tr, tbody , tr , td elements ; css

$(function() {
  var data = [{
    "X": [{
      "Time": "05:45",
      "Count": 70
    }, {
      "Time": "06:30",
      "Count": 40
    }, {
      "Time": "08:15",
      "Count": 80
    }]
  }, {
    "Y": [{
      "Time": "09:15",
      "Count": 70
    }, {
      "Time": "10:30",
      "Count": 84
    }, {
      "Time": "12:00",
      "Count": 95
    }]
  }, {
    "Z": [{
      "Time": "14:00",
      "Count": 80
    }, {
      "Time": "15:00",
      "Count": 70
    }, {
      "Time": "16:00",
      "Count": 40
    }]
  }];

  res = {};
  var table = $("<table><tbody></tbody></table>");
  $.each(data, function(key, value) {
    var name = Object.keys(value)[0];
    table.find("tbody")
    .append("<tr class=" + name + "><td>" + name + "</td></tr>");
    if (!res[name]) {
      res[name] = [];
    }

    $.each(value[name], function(index, obj) {
      res[name].push([obj.Count, obj.Time])
      table.append("<th>" + obj.Time + "</th>");
      return obj.Time
    });
    table.find("th").prependTo(table)
  });

  table.find("th:first").before("<th>Name</th>");

  $.each(res, function(index, count) {
    $("tr[class=" + index + "]", table).after(function() {
      return $.map(Array($("th", table).length - 1), function(v, k) {
        var html = count.filter(function(val) {
          return val[1] === $("th", table).eq(k + 1).text()
        });
        return "<tr><td>" + (!!html.length ? html[0][0] : 0) + "</td></tr>"
      })
    })
  });

  table.appendTo("body")
});
table tr:not([class]),
table th {
  display: inline-block;
}
table tr:not([class]) {
  width: 39px;
  position: relative;
  left: 44px;
  top:-24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks for your answer. This works fine. But I want to display X, Y, Z and its corresponding count to that particular time – Priya Sep 09 '15 at 05:07
1

You would have to correct your data so it is a proper object as show in the demo below.

  • First so that you may be able to iterate through the times combine all the array data into array, say a
  • Iterate through the keys of the object and the iterate through the elements of a
  • If current element of a exists in the value of the outer iteration, val, then output elm.Count, otherwise output 0.

var o = { 
    "X":[
        {"Time":"05:45","Count":70},
        {"Time":"06:30","Count":40},
        {"Time":"08:15","Count":80}
    ],
    "Y":[
        {"Time":"09:15","Count":70},
        {"Time":"10:30","Count":84},
        {"Time":"12:00","Count":95}
    ],
    "Z":[
        {"Time":"14:00","Count":80},
        {"Time":"16:00","Count":70},
        {"Time":"15:00","Count":40}
    ]
};
//merge arrays for purpose getting all times
var a = [];
$.each(o, function(k,v) {
    a = a.concat( v );
});

//select table
var table = $('table');

//create row to clone
var row = $('<tr/>');

//construct header
var theadRow = row.clone().html( '<th>Name</th>' );
$.each(a, function(i,v) {
    theadRow.append( '<th>' + v.Time + '</th>' );
});
//append header row to table
table.find('thead').append( theadRow );

//rows
var tbody = table.find('tbody');
$.each(o, function(key,val) {
    //construct row
    var tbodyRow = row.clone().html( '<th>' + key + '</th>' );
    $.each(a, function(index, elm) {
        tbodyRow.append( '<td>' + (val.indexOf( elm ) > -1 ? elm.Count : 0) + '</td>' );
    });
    //append row to table
    tbody.append( tbodyRow );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead></thead>
  <tbody></tbody>
</table>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
1

var data = {
    "X":[
        {"Time":"05:45","Count":70},
        {"Time":"06:30","Count":40},
        {"Time":"08:15","Count":80}
    ],
    "Y":[
        {"Time":"09:15","Count":70},
        {"Time":"10:30","Count":84},
        {"Time":"12:00","Count":95}
    ],
    "Z":[
        {"Time":"14:00","Count":80},
        {"Time":"16:00","Count":70},
        {"Time":"15:00","Count":40}
    ]
};

var keys = Object.keys(data), times = {}, rows = {};

(function processData(){
 
    var row, key, r;
    
    for(key in data) {
        row = rows[key] = {};
        for(r in data[key]) addInfo(row, data[key][r]);
    }
    
    function addInfo(row, record) {
        times[record.Time] = true;
        row[record.Time] = record.Count;
    }
    
})();

(function createTable() {
    
    var key,
        count,
        time,
        tr = $('<tr>'),
        $body = $('body'),
        $table = $('<table>'),
        $thead = $('<thead>'),
        $tbody = $('<tbody>');
    
    $body.append($table);
 $table.append($thead);
    $table.append($tbody);
    
    $thead.append(tr);
    
    tr.append('<th>name</th>');
    
    for(time in times) tr.append('<th>'+time+'</th>');
   
    for(key in rows) {
        tr = $('<tr>');
        tr.append('<th>'+key+'</th>');
        for(time in times) {
         count = (rows[key][time] || 0);
            tr.append('<td>'+count+'</td>');
        }
        $tbody.append(tr);
    }
        
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
flcoder
  • 713
  • 4
  • 14