Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

334
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda