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?
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?
Share Improve this question asked Nov 23, 2016 at 14:07 FabricioFabricio 7,93510 gold badges58 silver badges93 bronze badges2 Answers
Reset to default 16socket.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)))
.
You can parse the Map object to an object array just like this:
const myMap = new Map([
['key1', 'value1'],
['key2', 'value2'],
['key3', 'value3']
]);
const mapToArray = [];
for (const [key, value] of myMap.entries()) {
mapToArray.push({key: key, value: value});
}
console.log(mapToArray);
With this workaround you can have some funcionalities from map just using the array instance methods (filter, find, indexOf...)