Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
Fabricio Avatar asked Nov 23 '16 14:11

Fabricio


People also ask

How do you compare object and map?

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.

What is map () in JavaScript?

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.

Is map faster than object JavaScript?

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.


1 Answers

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))).

like image 146
Ahmed Fasih Avatar answered Oct 12 '22 13:10

Ahmed Fasih