1

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,,,

1 Answers1

0

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

jasonandmonte
  • 1,869
  • 2
  • 15
  • 24
  • Thank you @jasonandmonte it's a nice one but it return only first level of array. I'll try to modify it. `"","","","","","","","","","","","Credit Card","","" ` – Elodie Barrier May 09 '20 at 18:02