DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

8

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay