Home > Net >  How can I write a Map object to a CSV file with Node JS?
How can I write a Map object to a CSV file with Node JS?

Time:02-15

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?

CodePudding user response:

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

CodePudding user response:

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;
}
  • Related