How can I Display a JavaScript ES6 Map Object to Console?
you can use console.log(mapObject.values())
there is a more simpler solution you can try.
const mapObject = new Map();
mapObject.set(1, 'hello');
console.log([...mapObject.entries()]);
// [[1, "hello"]]
console.log([...mapObject.keys()]);
// [1]
console.log([...mapObject.values()]);
// ["hello"]
I realize this is most likely intended for the browser console but this also occurs in Node. So, you may use this in Node to view Maps (or an Object that may contain Maps):
import * as util from "util";
const map: Map<string, string> = new Map();
map.set("test", "test");
const inspected: string = util.inspect(map);
console.log(inspected);
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
)
*/