Fabricio Fabricio - 1 year ago 76
Node.js Question

How to emit a Map object

In the server side I have something like this:

const users = new Map();
users.set('id', { name: 'name' });
// ...

// then I emit:
io.emit('user_change', users);

In the client side I have something like:

socket.on('user_change', users => {
for (let user of users) {

is empty (

How do I emit a Map object?

Answer Source

socket.io (or whatever transport mechanism) is probably using JSON as the serialization format. Unfortunately, Maps and Sets and other ES2015 datatypes cannot be JSON-encoded.

let m = new Map([['one', 1], ['ten', 10], ['hundred', 100]]);
// "{}"

It’s very inelegant but I convert to an array-of-arrays on the server-side, transmit that, and recreate the map on the client:

let transitString = JSON.stringify(Array.from(m));
// "[["one",1],["ten",10],["hundred",100]]"
var newMap = new Map(JSON.parse(transitString));
// Map {"one" => 1, "ten" => 10, "hundred" => 100}

So in your case, I’d do io.emit('user_change', Array.from(users)); on the server, and on the client, change the for loop to consume a map: for (let user of (new Map(users))).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download