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,,,
3
  • Take a look at: stackoverflow.com/questions/11257062/… Commented May 9, 2020 at 17:36
  • this is not a csv format ( Comma Separated Values ) Commented May 9, 2020 at 17:37
  • mistake on my part. excel gave me a european csv format @Mister Jojo Commented May 9, 2020 at 18:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @jasonandmonte it's a nice one but it return only first level of array. I'll try to modify it. "","","","","","","","","","","","Credit Card","","" 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.