Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

380
Visualizações
Download an array as a CSV, but the data inside the array has commas in it

I have an array of arrays, which looks something like this:

rows = [
        [Name, Description, Number ...],
        ["A thing", "Description, but it has commas in it", 6, ...],
        ...
       ]

I am trying to download this as a csv file. Here's the code I have so far:

// Make a csv from rows
let csv = rows.map(row => row.join(",")).join("\n");

document.getElementById("csv_download").setAttribute("download", "file_name.csv");

document.getElementById("csv_download").href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);

This works fine when there are no commas inside the array, but right now it sees the comma after "Description" and splits it there. I also can't split it by ", because some of the items are numbers.

How do I go about solving this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

How do I go about solving this?

It varies. CSV is not a fully standardized format. But it will involve escaping those commas in the data in some way.

The most common way is to surround the fields that have commas with double quotes. If the data also has double quotes in it, you "escape" them with another double quote.

Applying that to your code:

let csv = rows.map(
    row => row.map(
        col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
    ).join(",")
).join("\n");

const rows = [
    ["Name", "Description", "Number"],
    ["A thing", "Description, but it has \"commas\" in it", 6],
];
let csv = rows.map(
    row => row.map(
        col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
    ).join(",")
).join("\n");
console.log(csv);

But again, that's just one way to handle it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda