I think your question is the ideal use case for a JS template library. Below is given the solution with handlebars: http://handlebarsjs.com/.
You only have to write your template:
<script id="template" type="text/x-handlebars-template">
{{#items}}
<tr><td>{{item}}</td><td>{{serving}}</td></tr>
{{/items}}
</script>
And then to compile it and inject it in your HTML page:
var tplScript = $("#template").html();
var template = Handlebars.compile (tplScript);
$("#genItems").html(template(food));
Below is the full code:
<script src="lib-js/jquery-1.11.1.min.js"></script>
<script src="lib-js/handlebars-v2.0.0.js"></script>
<body>
<table>
<thead>
<tr>
<th>Items</th>
<th>Servings</th>
</tr>
</thead>
<tbody id="genItems">
<!-- tr generated here -->
</tbody>
</table>
<script id="template" type="text/x-handlebars-template">
{{#items}}
<tr><td>{{item}}</td><td>{{serving}}</td></tr>
{{/items}}
</script>
<script>
var food = {};
food.items = [{
"item" : "Bread",
"serving" : "1",
"value" : "slice",
"amount" : 16,
"daily" : 2,
"used" : 8
},
{
"item" : "Cheese",
"serving" : "1",
"value" : "oz",
"amount" : 16,
"daily" : 2,
"used" : 8
},
{
"item" : "Crackers",
"serving" : "1",
"value" : "oz",
"amount" : 16,
"daily" : 2,
"used" : 8
}];
var tplScript = $("#template").html();
var template = Handlebars.compile (tplScript);
$("#genItems").html(template(food));
</script>
Note that JQuery is just used for convenience here.
Pros/Cons of this solution over a pure JS solution:
Pros:
- very concise
- clean: you don't mix your template with business logic
- preparation for next generation of web applications
Cons:
- not as performant as pure JS
Fiddle: http://jsfiddle.net/tr22rfmd/1/