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.


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 = => 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); = '_blank'; = 'export.csv';;
Enter fullscreen mode Exit fullscreen mode

Done. Your CSV gets download as show in below:

Image description

Always welcome any improvements.



Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post