How to write into a csv with multiple rows and columns
node.js
Solution
convert to nested arrays, join.
var array = [
{
title: "title_1",
content: "content_1",
author: "author_1"
},
{
title: "title_1",
content: "content_1",
author: "author_2"
}
];
var keys = Object.keys(array[0]);
var csv = [keys.join('\t')];
array.forEach(function (data) {
var row = [];
keys.forEach(function (key) {
row.push(data[key]);
});
csv.push(row.join('\t'));
});
csv = csv.join('\n');
output:
title content author
title_1 content_1 author_1
title_1 content_1 author_2
Problem
Now I have several JSON in my mongodb, such as: ``` { title: "title_1", content: "content_1", author: "author_1" } ``` And I want to write these data into a csv file with the format below: ``` title content author title_1 content_1 author_1 title_2 content_2 author_2 ... ``` I used the node-csv-parser module. But it always write in only the first column in the csv file, such as: ``` title content author title_1,content_1,author_1 title_1,content_1,author_2 ... ``` What should I do to achieve my aim? Please show me some examples. Any help would be greatly appreciated!