Search code examples
javascriptdictionaryecmascript-6console.logecmascript-2016

How can I Display a JavaScript ES6 Map Object to Console?


I'm using repl.it/languages/javascript.

Do I have to convert it to an object before I print it out?

I've tried

    const mapObject = new Map();
    
    mapObject.set(1, 'hello');
    
    console.log(JSON.stringify(mapObject));
    console.log(mapObject);

The results are always empty object.

When I use

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

It prints out an array format.


Solution

  • Note: This answer is only relevant to the repl.it sandbox environment OP is using

    Since you said in the comments that you're using repl.it, there's a trick you can use to write your own "logging strategy".

    Note that you shouldn't use this trick in production, mainly because it edits a native prototype. In some Node environment, in your own code, it could be useful though.

    The idea is to create an inspect method for Map that iterates over the entries:

    Map.prototype.inspect = function() {
      return `Map(${mapEntriesToString(this.entries())})`
    }
    
    function mapEntriesToString(entries) {
      return Array
        .from(entries, ([k, v]) => `\n  ${k}: ${v}`)
        .join("") + "\n";
    }
    

    You can see that repl.it supports it here

    console.log(new Map([["a", 1], ["b", 2]]));
    // Logs:
    /*
    Map(
      a: 1
      b: 2
    )
    */