Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  50] [ 2]  / answers: 1 / hits: 62253  / 7 Years ago, tue, august 8, 2017, 12:00:00

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.


More From » dictionary

 Answers
7

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
)
*/

[#56830] Saturday, August 5, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dawnc

Total Points: 612
Total Questions: 94
Total Answers: 98

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;