“Array JavaScript ke string CSV” Kode Jawaban

Array JavaScript ke string CSV

var colors = ["red", "blue", "green"];
var colorsString = colors.join(","); //"red,blue,green"
Friendly Hawk

JS Array ke CSV

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
Thoughtful Toad

Konversi array ke CSV JavaScript

var objectToCSVRow = function(dataObject) {
    var dataArray = new Array;
    for (var o in dataObject) {
        var innerValue = dataObject[o]===null?'':dataObject[o].toString();
        var result = innerValue.replace(/"/g, '""');
        result = '"' + result + '"';
        dataArray.push(result);
    }
    return dataArray.join(' ') + '\r\n';
}

var exportToCSV = function(arrayOfObjects) {

    if (!arrayOfObjects.length) {
        return;
    }

    var csvContent = "data:text/csv;charset=utf-8,";

    // headers
    csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));

    arrayOfObjects.forEach(function(item){
        csvContent += objectToCSVRow(item);
    }); 

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "customers.csv");
    document.body.appendChild(link); // Required for FF
    link.click();
    document.body.removeChild(link); 
}
Better Bat

Jawaban yang mirip dengan “Array JavaScript ke string CSV”

Pertanyaan yang mirip dengan “Array JavaScript ke string CSV”

Lebih banyak jawaban terkait untuk “Array JavaScript ke string CSV” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya