How does one convert an object into CSV using JavaScript?

arrays, csv, javascript, jquery

Solution

This is a simple implementation for TSV (for csv, see the comment on this answer):

// Returns a csv from an array of objects with
// values separated by tabs and rows separated by newlines
function CSV(array) {
    // Use first element to choose the keys and the order
    var keys = Object.keys(array[0]);

    // Build header
    var result = keys.join("\t") + "\n";

    // Add the rows
    array.forEach(function(obj){
        result += keys.map(k => obj[k]).join("\t") + "\n";
    });

    return result;
}

Problem

I want to convert this object into CSV file. The column names should be keys, this is small piece of array. And the last array will be only one of kind(keys), all other array will have same keys but different values. ``` [{ Comment: "Good", Experince Months: "4", Experince Years: "4", Score: "3", Subject: "CPP", Topic: "Scripting (mention details)" }, { Comment: "Excilent", Experince Months: "6", Experince Years: "6", Score: "6", Subject: "CSharp", Topic: "WPF" }, { Anything else worth highlighting: "Web Specialist", Result: "Selected", Total Business Analysis Experience: false, Total Project Management Experience: false, Total Score: 75, Total Server Side Development Experience: true, Total Server Side Support Experience: true, Total UI Development Experience: true, Total UI Support Experience: true }] ```

Original source

Related problems