Best way to parse JSON data into a table using javascript or jquery

时间:2015-08-07 01:57:16

标签: javascript jquery html json

I have document stored in database that holds the employees schedule for the week, which looks like so:

[ { _id: 55c407dc8ce6dfd4103c15db,
    'Last, First':
     { 'Mon   7/27': '10:15a-8:00p',
       'Wed   7/29': '10:15a-8:00p',
       'Fri   7/31': '10:30a-8:00p' },
    'Doe, John':
     { 'Tue   7/28': '2:00p-11:30p',
       'Thu   7/30': '8:00a-5:30p',
       'Sat   8/1': '10:15a-8:00p' }]

and then in my main page I have it load:

$(document).ready(function() {
  populateTable();
  ...}

function populateTable() {
$.getJSON('/download/download', function(data) {
 ???
}

The get Json works great and get the document perfectly. However, I'm not sure the best way to parse the information into a html table. Ideally I would want the table to look like this:

              Mon 7/27     Tue 7/28     Wed 7/29     Thu 7/30    Fri 7/31   Sat 8/1   Sun 8/2
Last, First  10:15a-8:00p             10:15a-8:00p
Doe, John                 2:00p-11:30p              8:00a-5:30p          10:15a-8:00p

I was wondering what the best way would be to do this within the populateTable() function. I am using jade for views and have the table set as so, but was wondering what the best way to append to it would be.

div.container
  div.content
    #mainTable
       table.table.table-striped
       thead
         tr
div.footer

Thanks!

1 个答案:

答案 0 :(得分:0)

As far as an implementation for populateTable() I'd do the following:

  1. Look at are which columns I'd need. Probably by looping through each employee in data, making a list of all the dates they are working.

  2. Create the row of headers by starting with an empty td and then creating a th for each date that anyone was working (created in step 1)

  3. Create a row for each employee, and for each day checking to see if their object in the JSON had a value for that day. If they did, output a td with their times, otherwise output an empty td.

That's the general scheme of how I'd go about designing populateTable()