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 Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved. This is not true in case of objects.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
numeric keys random(). toString() . The results are similar to those string-key cases: Map s start off as much faster than objects (2 times faster for insertion and deletion, 4-5 times faster for iteration), but the delta is getting smaller as we increase the size.
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)))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With