Last active
July 19, 2018 00:32
-
-
Save luislobo14rap/8d2c6845c568e9ea3bfcdaed0f91601e to your computer and use it in GitHub Desktop.
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
let objs = [ | |
{'id': '1', 'firstName': 'Alfred', 'lastName': 'Schmidt'}, | |
{'id': '2', 'firstName': 'Howard', 'lastName': 'Snyder'}, | |
{'id': '3', 'firstName': 'Yoshi', 'lastName': 'Latimer'} | |
]; | |
//optional | |
let getThis = [ | |
'id', | |
'firstName'//, | |
//'lastName' | |
]; | |
//optional | |
let header = [ | |
'ID', | |
'First name', | |
'Last name' | |
]; | |
/* | |
OR | |
let header = 1; | |
*/ | |
console.log( jsonToCSV(objs) ); | |
console.log( jsonToCSV(objs, 1) ); | |
console.log( jsonToCSV(objs, header) ); | |
console.log( jsonToCSV(objs, header, getThis) ); |
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
function jsonToCSV(objs, header = [''], getThis){ | |
if(objs.constructor == {}.constructor){ | |
objs = [objs]; | |
}; | |
if(typeof getThis == 'string'){ | |
getThis = [getThis]; | |
}else if(typeof getThis == 'undefined'){ | |
getThis = objs[0]; | |
getThis = Object.keys(getThis); | |
}; | |
if(typeof header == 'string'){ | |
header = [header]; | |
}else if(header === 1){ | |
header = getThis; | |
}; | |
let tab = ' '; | |
let spreadsheet = header.join(tab) + '\n'; | |
if(spreadsheet == '\n'){ | |
spreadsheet = ''; | |
}; | |
for(let i = 0; i < objs.length; i++){ | |
let thisObj = objs[i]; | |
for(let j = 0; j < getThis.length; j++){ | |
spreadsheet += thisObj[ getThis[j] ].toString().replace(/\t/g, ''); | |
if(j < getThis.length - 1){ | |
spreadsheet += tab; | |
}; | |
}; | |
if(i < objs.length - 1){ | |
spreadsheet += '\n'; | |
}; | |
}; | |
return spreadsheet; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment