DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

javascript: Object to CSV

This is a very much needed requirement in all most all web applications as and when backend doesn't support download for given results.

We generally populate results in table -> To populate we need to iterate over array contains data objects.

Like,

const data = [
{ name: 'Tom', id: '1234'},
{ name: 'James', id: '3456'},
{ name: 'Jerry', id: '7890'},
{ name: 'Peter', id: '4321'}
];
Enter fullscreen mode Exit fullscreen mode

And, the above forms table as:

Image description

Just want same results to be downloaded as CSV.

  const headers = Object.keys(data[0]).join();
    const content = data.map(value => Object.values(value).join());
    const csv = [headers].concat(content).join("\n");
    const element = document.createElement('a');
    element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
    element.target = '_blank';
    element.download = 'export.csv';
    element.click();
Enter fullscreen mode Exit fullscreen mode

Done. Your CSV gets download as show in below:

Image description

Always welcome any improvements.

Thanks.

Follow: https://twitter.com/urstrulyvishwak

Oldest comments (0)