Skip to content

Instantly share code, notes, and snippets.

@gabrielcsapo
Created December 8, 2016 18:00
Show Gist options
  • Save gabrielcsapo/63e41dd1620d5e41cfb662c1eb953c50 to your computer and use it in GitHub Desktop.
Save gabrielcsapo/63e41dd1620d5e41cfb662c1eb953c50 to your computer and use it in GitHub Desktop.
create an html table from a javascript object
var obj = [{
"key": "apple",
"value": 1.90,
"category": ["food", "fruit"],
"nutrition": {
"calories": 10
}
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}];
var keys = [];
var values = [];
obj.forEach(function(o, i){
values[i] = [];
Object.keys(o).forEach(function(k) {
if(keys.indexOf(k) <= -1) { keys.push(k) };
values[i].push(JSON.stringify(o[k]));
});
});
console.log(`
<table>
<thead>
${keys.map(function(k) {
return (`<th>${k}</th>`);
}).join('')}
</thead>
<tbody>
${values.map((v) => {
return (`
<tr>
${v.map(function(r) {
return (`<td>${r}</td>`)
}).join('')}
</tr>
`);
}).join('')}
</tbody>
</table>
`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment