Home > Software engineering >  Convert to String a map similar to console output via console.log([...mapObject.entries()])
Convert to String a map similar to console output via console.log([...mapObject.entries()])

Time:11-07

I have the following map:

  let mapObject = new Map();
  mapObject.set("one", "file1");
  mapObject.set("two", "file2");
  mapObject.set("three", "file3");

  console.log([...mapObject.entries()]);

and the console generates the following output:

[ [ 'one', 'file1' ], [ 'two', 'file2' ], [ 'three', 'file3' ] ]

I took this idea from this post, but this solution doesn't work if you add a string in the console statement:

console.log("This is a map: "   [...mapObject.entries()]);

it generates the following output instead:

This is a map: one,file1,two,file2,three,file3

which is less friendly to read. I would like in some how to have the same output I would obtain from: console.log([...mapObject.entries()]) but to be able to store it in a string for a general purpose. Is there a simple way to achieve it that works for google apps script?

CodePudding user response:

You can use JSON.stringify:

let mapObject = new Map();
mapObject.set("one", "file1");
mapObject.set("two", "file2");
mapObject.set("three", "file3");

const res = JSON.stringify([...mapObject.entries()])

console.log("This is a map: "   res);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related