如何使用JavaScript将对象转换为CSV?

Use*_*038 8 javascript csv arrays jquery

我想将此对象转换为CSV文件.列名应该是键,这是一小块数组.并且最后一个数组将只是一种(键),所有其他数组将具有相同的键但不同的值.

[{
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
}]
Run Code Online (Sandbox Code Playgroud)

650*_*502 11

这是一个简单的实现:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 唯一的事情 - 您创建 TSV(制表符分隔值),而不是 CSV。如果您需要 CSV - 用逗号符号替换 \t (3认同)