首页 > 解决方案 > Node / Javascript:如何将键值对数组写入csv文件,键作为标题?

问题描述

使用 Node.js,我将如何从包含键值对的数组中写出 csv 文件?

这是我想写出的键/值对的示例数组。

function testWriteCsv() {
    const arr = []
    const kp1 = []
    const kp2 = []
    const kp3 = []

    kp1['FIRST_NAME'] = 'First Name1';
    kp1['LAST_NAME'] = 'First Name1';

    kp2['FIRST_NAME'] = 'First Name2';
    kp2['LAST_NAME'] = 'First Name2';

    kp3['FIRST_NAME'] = 'First Name3';
    kp3['LAST_NAME'] = 'First Name3';

    arr.push(kp1)
    arr.push(kp2)
    arr.push(kp3)

    console.log('arr', arr)

    // now I want to write out a .csv file of the above data, with header:
    // FIRST_NAME,LAST_NAME
}

我按照示例尝试使用以下库,但它们都不适用于键值对数组。

以下库都没有我可以传递键/值对数组并帮助写出 .csv 的函数。

我尝试使用以下库来扭曲数组、交互、做各种事情,但它们都不起作用。

fs
fast-csv
convert-array-to-csv
csv-writer

我会问,如果你以前做过,并且有一个完整的例子,请分享,将不胜感激。

谢谢你。


更新:

这是一个解决方案的完整工作示例:

const fs = require('fs');

function testWriteCsv() {
    const arr = [];
    const kp1 = [];
    const kp2 = [];
    const kp3 = [];

    kp1['FIRST_NAME'] = 'First Name1';
    kp1['LAST_NAME'] = 'First Name1';

    kp2['FIRST_NAME'] = 'First Name2';
    kp2['LAST_NAME'] = 'First Name2';

    kp3['FIRST_NAME'] = 'First Name3';
    kp3['LAST_NAME'] = 'First Name3';

    arr.push(kp1);
    arr.push(kp2);
    arr.push(kp3);

    // 'output' will hold the full csv result to be written to file
    const headers = Object.keys(arr[0]);
    let output = headers.join() + '\n';

    for (let kv of arr) {
        let values = Object.values(kv).join() + '\n';
        output += values
    }

    // Write to a file
    fs.writeFile("test.csv", output, function (err) {
        if (err) return console.log(err);
        console.log("The file was saved!");
    });
}

testWriteCsv()

标签: javascriptarraysnode.jscsvkey-value

解决方案


这可能可以用你提到的一个库做得更好,但我猜你的问题是将数组解构为一个可以保存到文件中的字符串,所以我留下一个简单的例子:

// Required for writing into file (writeFile())
const fs = require('fs');

// Constructing the array (same as original)
const arr = [];
const kp1 = [];
const kp2 = [];
const kp3 = [];

kp1['FIRST_NAME'] = 'First Name1';
kp1['LAST_NAME'] = 'Last Name1';

kp2['FIRST_NAME'] = 'First Name2';
kp2['LAST_NAME'] = 'Last Name2';

kp3['FIRST_NAME'] = 'First Name3';
kp3['LAST_NAME'] = 'Last Name3';

arr.push(kp1);
arr.push(kp2);
arr.push(kp3);

// Output will hold the whole text, starting with the Header
output = Object.keys(arr[0]).join(',') + '\n';

// Add line by line to the output
for(kp of arr) {
    output += Object.values(kp).join(',') + '\n';
}

// Write to a file
fs.writeFile("test.csv", output, function(err) {
    if(err) return console.log(err);
    console.log("The file was saved!");
}); 

这将生成以下输出变量(并将其保存到文件中):

FIRST_NAME,LAST_NAME
First Name1,Last Name1
First Name2,Last Name2
First Name3,Last Name3

如果这对您有用,您可以将逻辑拆分为单独的函数或使用您认为合适的库。

// 编辑

生成输出的旧方式,供参考:

// Get headers from the keys from the first child of the array (arr[0] would be kp1)
let [col1, col2] = Object.keys(arr[0]);

// Output will hold the whole text, starting with the Header
output = col1 + ',' + col2 + '\n';

// Add line by line to the output
for(let i = 0; i < arr.length; i++) {
    output += arr[i][col1] + ',' + arr[i][col2] + '\n';
}

推荐阅读