This function is meant to take an object, loop through the key-values and generate/build a HTML table at a particular ID:
function insertBasicTable(basic_data, insert_id) { /* Insert the key/value pairs into a table element on the DOM. basic_data = object containing key/value pairs insert_id = the id on the DOM to insert the table into Intentionally not including closing tags in the jquery requests; http://stackoverflow.com/a/14737115/2355035 */ table_id = '#' + insert_id; var array_length = Object.keys(basic_data).length; var array_obj_names = Object.keys(basic_data); // create the table header $(table_id).empty(); $(table_id).append('<thead>'); $(table_id).find('thead:last').append('<th>Tag'); $(table_id).find('thead:last').append('<th>Data'); // begin the table body and iterate through key/value pairs $(table_id).append('<tbody>'); for (var i = 0; i < array_length; i++) { var attr_name = array_obj_names[i]; var tag = '<td>' + array_obj_names[i]; var data = '<td>' + basic_data[attr_name]; $(table_id).find('tbody:last').append('<tr>' + tag + data); } }
This function is then used, along with a number of D3 scripts, to populate elements on the DOM:
linePlot.render(someObject.modules.qual.quintiles); boxPlot.render(someObject.modules.qual.quintiles); insertBasicTable(someObject.modules.basic, 'basic-stats-table'); // etc, etc...
Any comments about how this is being achieved? Am I overlooking either a basic tenant of how JS "should" be used (this is a huge side-effect for instance, should I be returning a formatted string then placing that string into the DOM for instance) or over-complicating things by jQuery'ing a bunch of times?