Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one convert an object into CSV using JavaScript?

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
}]
like image 785
User1038 Avatar asked Apr 01 '14 11:04

User1038


People also ask

How do you convert an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

How do I write an object to a csv file?

First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.


1 Answers

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;
}
like image 90
6502 Avatar answered Nov 06 '22 20:11

6502