I'm trying to convert this Javacript Object into a CSV file without any frameworks just in vanilla JS
Following are my json :
[{
customer_details: {
firstName: "SEBO",
lastName: "RAQUI",
address1: "1990 empty road",
address2: "",
address3: "",
zipcode: "99199",
country: "US",
},
order_details: {
items: [
{
listPrice: 14,
productID: "IEBPTDIEBAIEB119SJM",
quantity: 11,
description: "RED SHOES",
},
{
listPrice: 9,
productID: "PTDIIEB2886JG10",
quantity: 8,
description: "WHITE SHIRT",
},
],
},
payment: "AMEX",
shipping: { type: "Express", HSCode: "ARKA10" },
}]
following is the csv format output
customer_details.firstname,customer_details.lastname,customer_details.address1,customer_details.address2,customer_details.address3,customer_details.zipcode,customer_details.country,order_details.items.listPrice,order_details.items.productID,order_details.items.quantity,order_details.items.description,payment,shipping.type,shipping.HSCode
SEBO,RAQUI,1990 empty road,,,99199,US,14,EBPTDIEBAIEB119SJM,11,RED SHOES,AMEX,Express,ARKA10
,,,,,,,9,PTDIIEB2886JG10,8,WHITE SHIRT,,,
-
Take a look at: stackoverflow.com/questions/11257062/…Asier Gomez– Asier Gomez2020年05月09日 17:36:36 +00:00Commented May 9, 2020 at 17:36
-
this is not a csv format ( Comma Separated Values )Mister Jojo– Mister Jojo2020年05月09日 17:37:00 +00:00Commented May 9, 2020 at 17:37
-
mistake on my part. excel gave me a european csv format @Mister JojoElodie Barrier– Elodie Barrier2020年05月09日 18:05:49 +00:00Commented May 9, 2020 at 18:05
1 Answer 1
Try this:
const JSONtoCSV = (arr, columns, delimiter = ';') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
I modified the delimited to use semicolons like your example showed.
Resource: https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/JSONtoCSV.md
answered May 9, 2020 at 17:44
jasonandmonte
2,0382 gold badges18 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Elodie Barrier
Thank you @jasonandmonte it's a nice one but it return only first level of array. I'll try to modify it.
"","","","","","","","","","","","Credit Card","","" lang-js