How to fix Map object

On 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);

On the client side there is something like:

socket.on('user_change', users => {
    for (let user of users) {
        userlist.append(`<li>${user.name}</li>`);
    }
});

But usersempty ( {}).

How do I select a Map object ?

+4
source share
1 answer

socket.io (or any other transport mechanism) probably uses JSON as its serialization format. Unfortunately, maps and sets and other ES2015 data types cannot be encoded in JSON.

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

Its very inelegant, but I convert it to an array of arrays on the server side, pass it 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}

, Id do io.emit('user_change', Array.from(users)); for, : for (let user of (new Map(users))).

+1

Source: https://habr.com/ru/post/1661718/


All Articles