Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript array to csv string

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

js array to csv

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

js array to csv download

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|
)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '
';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}
Comment

js array to csv download

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("
");
Comment

convert array to 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(' ') + '
';
}

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); 
}
Comment

javascript array to csv

/** Convert a 2D array into a CSV string
 */
function arrayToCsv(data){
  return data.map(row =>
    row
    .map(String)  // convert every value to String
    .map(v => v.replaceAll('"', '""'))  // escape double colons
    .map(v => `"${v}"`)  // quote it
    .join(',')  // comma-separated
  ).join('
');  // rows starting on new lines
}

/** Download contents as a file
 * Source: https://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side
 */
function downloadBlob(content, filename, contentType) {
  // Create a blob
  var blob = new Blob([content], { type: contentType });
  var url = URL.createObjectURL(blob);

  // Create a link to download it
  var pom = document.createElement('a');
  pom.href = url;
  pom.setAttribute('download', filename);
  pom.click();
}

downloadBlob(csv, 'export.csv', 'text/csv;charset=utf-8;')
Comment

PREVIOUS NEXT
Code Example
Javascript :: foreach break js 
Javascript :: javascript variable with multiline text 
Javascript :: joi unique validation 
Javascript :: check for duplicates in array javascript 
Javascript :: upload preview image js 
Javascript :: remove comma from string jquery 
Javascript :: react slick 
Javascript :: javaScript setSeconds() Method 
Javascript :: how to unban in discord js 
Javascript :: javascript get specific timezone 
Javascript :: react native webview not working 
Javascript :: react append classname 
Javascript :: js get time 
Javascript :: window load 
Javascript :: jquery change select value 
Javascript :: javascript currency format 
Javascript :: create new element 
Javascript :: remove hostname from url javascript 
Javascript :: javascript getcontext 
Javascript :: how to delete a letter from a string in javascript 
Javascript :: integer to array javascript 
Javascript :: javascript set input value by id 
Javascript :: set attribute javascript 
Javascript :: how to rotate an array in javascript 
Javascript :: find a word in string javascript 
Javascript :: vanilla javascript change background color 
Javascript :: usereducer hook 
Javascript :: react native red triangle up 
Javascript :: get id of an element 
Javascript :: Difference in push and navigate in react Navigation 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =