Last active
March 15, 2019 12:54
-
-
Save perymimon/2f2bdfcdeb61088b4ef2131fd5397253 to your computer and use it in GitHub Desktop.
tiny code to convert array of objects to headers and rows.
For easy print to console. or create to html table
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
var data = [{a:1, b:2},{c:3,b:2},{d:4,a:1}]; | |
objectsToTableRows(data); | |
/* return ... | |
{ | |
headers:(4) ["a", "b", "c", "d"], | |
rows:Array(3) | |
0:(2) [1, 2] | |
1:(3) [undefined × 1, 2, 3] | |
2:(4) [1, undefined × 2, 4] | |
length:3 | |
}*/ |
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 objectsToTableRows(objects){ | |
// all object headers to Set and back to Array; | |
const headers = [ ...new Set( objects.map( o => Object.keys(o) ).flat() ) ], | |
rows = objects.map( o => headers.map( h => o[h] ) ) | |
return {headers,rows}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment