Skip to content

Instantly share code, notes, and snippets.

@jdittrich
Last active August 25, 2017 08:48
Show Gist options
  • Save jdittrich/047d18abcdd377e52fbafa31e7f1f49d to your computer and use it in GitHub Desktop.
Save jdittrich/047d18abcdd377e52fbafa31e7f1f49d to your computer and use it in GitHub Desktop.
JSON to CSV
//Data for testing it
var dataobject = {
rows:[
{Preis:"100",Geraet:"Android Phone"},
{Preis:"600",Geraet:"iPad"},
{Preis:"1000",Geraet:"Thinkpad"}
]
};
//get all column names. Use the first object in rows for that.
// we write it in a variable here as an array so we can ensure the same order every time we collect the keys.
var colnames = Object.keys(dataobject.rows[0]);
//GETS:
// colnames: an array with column names as strings: ["name2", "name2",…]
// lineObject: An object with keys/values. Keys need to be corresponding to the strings in colnames.
//RETURNS:
// an array with all values from lineObject in order of the keys in colnames
var getSingleLineArray = function(colnames,lineObject){
var lineArray =[];
colnames.forEach(function(currentColName){
lineArray.push(lineObject[currentColName]);
});
return lineArray;
};
//Gets an array in which each item is an object with key/value pairs. Each key signifies a table column name, each value a value/cell in a table.
var csv = dataobject.rows.reduce(function(prevVal, objectRow){
var lineArray = getSingleLineArray(colnames, objectRow);
var lineConcat = lineArray.join(",")+"\n";
return prevVal+lineConcat;
},colnames.join(",")+"\n");
console.log(csv);
/*
Preis,Geraet
100,Android-Phone
600,iPad
1000,Thinkpad
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment