现在我的mongodb中有几个JSON,例如:
{
title: "title_1",
content: "content_1",
author: "author_1"
}
我想将这些数据写入csv文件,格式如下:
title content author
title_1 content_1 author_1
title_2 content_2 author_2
...
我使用了node-csv-parser模块。但它始终只写入csv文件的第一列,例如:
title content author
title_1,content_1,author_1
title_1,content_1,author_2
...
我应该怎样做才能实现目标?请给我看一些例子。任何帮助将不胜感激!
答案 0 :(得分:5)
转换为嵌套数组,加入。
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');
输出:
title content author
title_1 content_1 author_1
title_1 content_1 author_2
答案 1 :(得分:0)