0

Let's say I have a Map:

const m = new Map([[1,1], [2,2], [3,3]]);

What's the quickest method to inline it in template literal in a manner that it will look like this:

enter image description here

or any other readable format?

P.S. This won't work:

const str = `${m}`;
zmii
  • 4,123
  • 3
  • 40
  • 64

2 Answers2

3

You could take a function for it, which takes the map and creates a string.

function beautify(o) {
    if (o instanceof Map) {
        return 'Map(' + JSON.stringify(Array.from(o.entries())) + ')';
    }
    return o;
}


const m = new Map([[1,1], [2,2], [3,3]]);
console.log(beautify(m));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for answer, I've extracted needed part to other answer. Upvoting yours answer as it's more universal. – zmii Jul 13 '18 at 09:04
0

Simplifying Nina Scholz answer, I would go with either with

console.log(` something => ${JSON.stringify([...m])}`);

or with

console.log(` something => ${JSON.stringify(Array.from(m))}`);
zmii
  • 4,123
  • 3
  • 40
  • 64