Created
May 12, 2016 18:45
-
-
Save liamzdenek/b909079e686fbfefd74c93101d5aca13 to your computer and use it in GitHub Desktop.
Render Left Join into HTML using JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function render_rows(rows) { | |
// html is a variable that contains a html string that we're going to build dynamically | |
var html = "", | |
// cur_msg_id keeps track of which message_id we are currently printing the comments of | |
cur_msg_id = 0; | |
// begin a loop over each row within the table | |
for(i = 0; i < rows.length; i++) { | |
// store the message id of this row for later use | |
cur_msg_id = rows[i]['message_id']; | |
// print out the message | |
html += '<div class="wrapper">'; | |
html += 'Message: ' + rows[i]['message']+"<br/>"; | |
// if there is at least one comment... | |
if(rows[i]['comment_id'] != null) { | |
// begin a loop over the comments | |
html += '<div class="comments">'; | |
for(; i < rows.length; i++) { | |
// print out the comment | |
html += '<div class="comment">' | |
html += 'Comment: ' + rows[i]['comment'] + ' - ' | |
html += 'Author: ' + rows[i]['first_name'] + ' ' + rows[i]['last_name'] | |
html += '</div>' // close comment | |
// if the next row exists and that row's message id is different than the current message id, break | |
if(rows.length > i+1 && rows[i+1]['message_id'] != cur_msg_id){ | |
break; | |
} | |
} | |
html += '</div>' // close comments | |
} | |
html += '</div>' // close wrapper | |
} | |
// store the resulting html in the document | |
document.body.innerHTML = html; | |
} | |
var rows = [ | |
{"message_id": 1, "message":"hello", "comment_id":"1", "comment":"Hello 1", "user_id":"1", "first_name": "Tom", "last_name": "Testington"}, | |
{"message_id": 1, "message":"hello", "comment_id":"2", "comment":"Hello 2", "user_id":"1", "first_name": "Tom", "last_name": "Testington"}, | |
{"message_id": 1, "message":"hello", "comment_id":"3", "comment":"Hello 3", "user_id":"2", "first_name": "Mary", "last_name": "Madeuperson"}, | |
{"message_id": 1, "message":"hello", "comment_id":"4", "comment":"Hello 4", "user_id":"2", "first_name": "Mary", "last_name": "Madeuperson"}, | |
{"message_id": 2, "message":"bye", "comment_id":null, "comment":null, "user_id":null, "first_name": null, "last_name": null}, | |
{"message_id": 3, "message":"asdf", "comment_id":"5", "comment":"Hello 5", "user_id":"1", "first_name": "Tom", "last_name": "Testington"}, | |
{"message_id": 4, "message":"zyx", "comment_id":null, "comment":null, "user_id":null, "first_name": null, "last_name": null}, | |
]; | |
document.addEventListener("DOMContentLoaded", function(e){ | |
render_rows(rows); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment