Fabricio Fabricio - 16 days ago 8
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) {
userlist.append(`<li>${user.name}</li>`);
}
});


But
users
is empty (
{}
).

How do I emit a Map object?

Answer

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]]);
console.log(JSON.stringify(m));
// "{}"

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));
console.log(transitString)
// "[["one",1],["ten",10],["hundred",100]]"
var newMap = new Map(JSON.parse(transitString));
console.log(newMap)
// 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))).