Created
December 8, 2016 18:00
-
-
Save gabrielcsapo/63e41dd1620d5e41cfb662c1eb953c50 to your computer and use it in GitHub Desktop.
create an html table from a javascript object
This file contains hidden or 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
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