0

I have a javascript object of the format,

obj= {name:"name", phone:"phone" , email:"email"}

I want this to be downloaded on click of a button as a CSV file.

var list = []
var saveids = function(){
   obj.forEach(function(userrecord){
      list.push([obj.name,obj.email,obj.phone]);
   });
   window.open("data:text/octet-stream;charset=utf-8," + escape(list));
}

UI Part

$('#saveids').click(function(){
    saveids();
}

This opens a new window with all the data in a single continuous line.

I cant figure out how to properly format the data as CSV and how to make the <a #saveids> generate a download file link.

1
  • 1
    That's two different questions. Serializing CSV is a solved problem, please search harder. Commented Mar 1, 2014 at 13:21

2 Answers 2

1

To download a list as CVS you can simply do:

var forEach = Array.prototype.forEach,
    list = [
      {id: 1, name: 'Luke', phone: '999 999 999'},
      {id: 2, name: 'Yoda', phone: '999 222 333'}
    ],
    clipboard = "id,name,phone\n";

forEach.call(list, function(item){
    clipboard += item.id + "," + item.name + "," + item.phone + "\n";
});

content = "data:text/csv," + encodeURIComponent(clipboard);
location.href = content;

Open the Developer Tools > Console and run this code to see it in action.

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

1 Comment

It is same as my code, a bit worse, as it takes over the current page. My code opens a new window, what I really need a download to be initiated in the browser automatically.
0

Following code snippet will take the array of object and make csv, the object keys will be header titles and rest will be values, and download automatically:-

function convertObjectListToCSV(dataObjectList) {


    var replacer = (key, value) => value === null ? '' : value // handle null values

    var header = Object.keys(dataObjectList[0])

    let csv = dataObjectList.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))

    csv.unshift(header.join(',')); //headers will be first row

    csv = csv.join('\r\n');//next row distinguished by '\r\n' in CSV


    var fileName = 'yourCsvFile.csv';//later can be dynamic name 

    // downloading file procedure, by oneshubh
    var downloadLink = document.createElement("a");
    downloadLink.download = fileName;
    downloadLink.href = window.URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    downloadLink.click();// we need to revoke URL later
    // downloading file procedure end
}

Usage Ex:-

convertObjectListToCSV([{name:"name", phone:"phone" , email:"email"},
{name:"name1", phone:"phone1" , email:"email1"}])

working code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.