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

335
Visualizações
How can I write a Map object to a CSV file with Node JS?

I have a map:

const map = new Map()

In this map I have the values:

{
  'contract' => [ 'MetaCoin.sol', 'MetaCoin.sol', 'MetaCoin.sol', 'MetaCoin.sol' ],
  'hash' => [ '1bb0ff1c', '330f7461', '07c815a6', '8166ca06' ],
  'operator' => [ 'AOR', 'AOR', 'AOR', 'AOR' ],
  'TestMetaCoin' => [ 'L', 'L', 'L', 'L' ],
  'Contract: MetaCoin' => [ 'K', 'K', 'K', 'L' ]
}

I need to write this map in a CSV file that contains my keys like a column name and the values ​​associated with the column titles in the column below them in this way:

enter image description here

How can I write my CSV file?

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

0

You can create a csv file string and use fs to write to a file like this;

First looping through all the keys to create the header

    var myStr = ""
    // Creating header
    for(let key of map.keys()){
      myStr += key+","
    } 
    myStr = myStr.slice(0,-1)+"\r\n";

Getting the first array using map.values()

const [firstValue] = map.values();

Now looping through all the keys and getting a particular element from all the arrays an creating a row for a csv file

    // Creating each row
 for(let i = 0; i<firstValue.length; i++){
     var row = ""
     for(let key of map.keys()){
      if(map.get(key)[i]){
       row += map.get(key)[i]+","
      }else{
        row += ","
      }
     }
     myStr += row.slice(0, -1)+"\r\n";
    }

Saving the string to the csv file

fs.writeFileSync('./mycsv.csv',myStr);
about 4 years ago · Juan Pablo Isaza Relatório

0

The usual convention is that the first line contains the column names/titles, with the remaining lines being the data.

To accomplish that (assuming that your data is contained in a Map or WeakMap), you can do something like this:

function toCSV( map = new Map() ) {
  const header  = Array.from( map.keys() )
                  .join(",")
                  ;
  const records = Array.from( map.values() )
                  .map( arr => arr.join(",") )
                  ;
  const csv = [
    headers,
    ...records,
  ].join("\n");

  return csv;
}
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