0

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?

2
  • Do you have an example of the code you've tried? SO isn't supposed to be a code writing service. Commented Feb 14, 2022 at 18:25
  • is [...map] a good start? returns [ [ 'contract', [ 'MetaCoin.sol', 'MetaCoin.sol', 'MetaCoin.sol', 'MetaCoin.sol' ] ], [ 'hash', ['1bb0ff1c', ... Commented Feb 14, 2022 at 18:28

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Be a better answer if you explained what the code does instead of the code dump.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.