Search code examples
javascriptecmascript-6es6-map

How to get content of Map object in JS template literal in readable format?


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}`;

Solution

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